CS.EXCEPT.RETHROW
Avoid clearing stack trace while rethrowing exceptions.
Avoid rethrowing the caught exception because this will re-throw the exception and clear the stack trace. On the other hand a simple "throw;" will re-throw the caught expression and retain the stack trace. If you really need to add additional information and throw a new exception, then you should preserve the original exception as an InnerException in the newly thrown exception.
Vulnerable code example
1 public class Class1 2 { 3 public void method1() 4 { 5 try 6 { 7 // Code 8 } 9 catch (Exception ex) 10 { 11 // Exception handling code 12 throw ex; // Violation 13 } 14 } 15 }
Fixed code example
1 public class Class1 2 { 3 public void method1() 4 { 5 try 6 { 7 // Code 8 } 9 catch (Exception ex) 10 { 11 // Exception handling code 12 throw; // FIXED 13 } 14 // alternative 15 try 16 { 17 // Code 18 } 19 catch (Exception ex) 20 { 21 // Exception handling code 22 Exception ex2 = new Exception("more info", ex); 23 throw ex2; // FIXED, added more info to the exception 24 } 25 } 26 }