A quick tip on catching and throwing exceptions.
General way of throwing exceptions:
try
{
-----------------------
your code
-----------------------
}
catch(Exception ex)
{
----any clean up activities-----
throw ex;
}
Recommended way of throwing exceptions:
1. If you want to just do some cleanup when an exception occurs, you should re-throw the caught exception using this code instead:
catch(Exception)
{
---- clean up activities -----;
throw;
}
This preserves the original calling stack. Nobody knows you were involved, and they can trace back to the exception from its true origin without being diverted into your cleanup code. the above examle belongs to this category.
2. If you want to be part of the exception chain, then you should re-package the exception with your own, and assign the old one as the inner exception:
catch(Exception exception)
{
---clean up activities -----;
throw new MyException(exception);
}
You turn the general exception into a specific one, while preserving the original inner exception so that it can continue to be traced back to the origin.
No comments:
Post a Comment