Red > Green > Refactor > Red

cycle is based on desire

try and re-throw best practice

quoted literal and source code from:

IBM Best Practice: Catching and re-throwing Java Exceptions - United States

  • re-throw is ok
  • notice the way to re-throw

Correct

The correct way to catch and re-throw an exception

is to pass the caught exception object as the "rootCause"

or inner exception parameter to the constructor of the new exception

(note that not all exception constructors support inner exceptions,

in which case a different wrapper exception should be used).

When the exception is later caught and printed to SystemOut.log,

the inner exception message and stack will be included:
// #4. Correct. Note the exception, t, is passed as the second 
//     parameter to the ServletException constructor. 
try { 
     // do work 
} catch (Throwable t) { 
     throw new ServletException("Error: " + t.getMessage(), t); 
} 

// #5. Also correct. 
try { 
     // do work 
} catch (Throwable t) { 
     try { 
          // Perform some application logging or auditing 
          // e.g. t.printStackTrace(); 
     } catch (Throwable tAppDebug) { 
          tAppDebug.printStackTrace(); 
          throw t; 
     } 
} 

Incorrect

// #1. Worst -- there is no indication that an exception 
// occurred and processing continues. 
try { 
     // do work 
} catch (Throwable t) { 
} 

// #2. Very Bad -- there is an indication that an 
// exception occurred but there is no stack trace, and 
// processing continues. 
try { 
     // do work 
} catch (Throwable t) { 
     System.err.println("Error: " + t.getMessage()); 
} 

// #3. Incorrect. The stack trace of the original 
// exception is lost. In the case of an Exception such as 
// a NullPointerException, getMessage() will return a 
// blank string, so there will be little indication of 
// the problem. 
try { 
     // do work 
} catch (Throwable t) { 
     throw new ServletException("Error: " + t.getMessage()); 
}