How to Rethrow an Exception
When catching an exception in a language like C#, sometimes it's helpful to rethrow the exception to let some outer calling method handle the exception.
Example 1 (incorrect method):
catch (Exception ex) { throw ex; }
Example 2 (correct method):
catch (Exception ex) { throw; }
In the first example, a new exception is made based on the caught exception, but this new exception loses the stack trace of the original exception. The second example is truly rethrowing the original exception and the stack trace is preserved.
In many cases, a programmer will want to add some data to an exception before it's rethrown. There are two main methods for doing this.
Method 1:
Method 2:
In the first method, a new Exception type is created that contains the original exception. This is handy for cases where the logical exception has changed and the name should therefore change to reflect this.
In most cases, the type of exception is the same, but the current catch block is simply adding some extra debug information to the exception. In this case, use the second method shown above. Here we are simply adding some data to the current exception before rethrowing it. This data is being added to a Dictionary, and is therefore structured as a key/value pair. Both the key and value are of type object, but the key should be a string when possible.
Customizing the Rethrown Exception
In many cases, a programmer will want to add some data to an exception before it's rethrown. There are two main methods for doing this.
Method 1:
catch (Exception ex) { throw new CustomException("This is some custom data", ex); }
Method 2:
catch (Exception ex) { ex.Data.Add("CustomData", "This is some custom data"); throw; }
In the first method, a new Exception type is created that contains the original exception. This is handy for cases where the logical exception has changed and the name should therefore change to reflect this.
In most cases, the type of exception is the same, but the current catch block is simply adding some extra debug information to the exception. In this case, use the second method shown above. Here we are simply adding some data to the current exception before rethrowing it. This data is being added to a Dictionary, and is therefore structured as a key/value pair. Both the key and value are of type object, but the key should be a string when possible.
No comments:
Post a Comment