Pages

Tuesday, April 26, 2016

c# try and catch

DO NOT DO THIS. If an exception is thrown in CallMethod() and it gets bubbled up to this try/catch, you must use “throw;” to rethrow the exception. “throw;” will preserve the stack trace while “throw ex;” will make it look like the exception originated here. This can cause much confusion when trying to debug exception statements.

try
{
    CallMethod();                         
}
catch (Exception ex)
{
    SMXLog.LogException(ex);
    throw ex;
}



 If all that is happening in the catch block is a re-throw, then you do not need this Try/Catch at all. The try/catch is redundant and does nothing extra. In the above example, it is ok to use a try/catch with “throw;” because the catch block is Logging (doing something).

try
{
   CallMethod();                      
}
catch (Exception ex)
{
    // If the only thing being done in the Catch block is a re-throw,
    // then the entire try/catch block is redundant/not needed.
    throw;  
}


     https://stackoverflow.com/questions/881473/why-catch-and-rethrow-an-exception-in-c (good overview)

http://stackoverflow.com/questions/22623/throwing-exceptions-best-practices

using just "throw" will only bubble up a message that an exception occurred at the "throw" line rather than the actual line where exception occurred.

using "throw new exception" will preserve the stack trace with exact line of fault. but need to use parameters that allow the details to bubble up.

both examples work. first is if you want to include some extra detail but not necessary as each displays a very detailed message.