When re-throwing an exception, make sure to include the stack trace. Otherwise pertinent debug information is lost.
1public void throwExceptionWithTraceNoncompliant() throws Exception {
2 try {
3 doSomething();
4 } catch (Exception e) {
5 // Noncompliant: the new exception only has the message from the original exception.
6 throw new Exception("Error: " + e.getMessage());
7 }
8}
1public void throwExceptionWithTraceCompliant() throws Exception {
2 try {
3 doSomething();
4 } catch (Exception e) {
5 // Compliant: the new exception contains the original exception.
6 throw new Exception("Error: " + e.getMessage(), e);
7 }
8}