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
Copy
public class Class1
{
public void method1()
{
try
{
// Code
}
catch (Exception ex)
{
// Exception handling code
throw ex; // Violation
}
}
}
Fixed code example
Copy
public class Class1
{
public void method1()
{
try
{
// Code
}
catch (Exception ex)
{
// Exception handling code
throw; // FIXED
}
// alternative
try
{
// Code
}
catch (Exception ex)
{
// Exception handling code
Exception ex2 = new Exception("more info", ex);
throw ex2; // FIXED, added more info to the exception
}
}
}