On Apr 29, 7:04*am, RedLars <Liverpool1...@gmail.com> wrote:
> Say I have the following structure of code in three different
> locations in a project. There are actually 8 different exceptions,
> only showed 4 for brevity. In the first location all 8 exceptions are
> relevant but in the two other locations only 6 exceptions are
> relevant. The handling of each exception would be the same for all 3
> locations.
>
> try
> {
> * // do stuff}
>
> catch (MyExceptionX1 x1)
> {
> * // do logging
> * // do action}
>
> catch (MyExceptionX2 x2)
> {
> * // do logging
> * // do action}
>
> catch (MyExceptionX3 x3)
> {
> * // do logging
> * // do action}
>
> catch (MyExceptionX4 x4)
> {
> * // log
> * // do action
>
> }
>
> To reduce duplicate code would something like this be sensible;
>
> try
> {
> * // do stuff}
>
> catch (Exception e)
> {
> * * * * HandleExceptions(e);
>
> }
>
> public static MyExceptionClass
> {
> public static void HandleExceptions(Exception e)
> {
> * * * * MyExceptionX1 x1 = e is MyExceptionX1;
> * * * * if (x1 != null)
> * * * * {
> * * * * * * * * // log
> * * * * * * * * // do action
> * * * * * * * * return
> * * * * }
>
> * * * * MyExceptionX2 x2 = e is MyExceptionX2;
> * * * * if (x2 != null)
> * * * * {
> * * * * * * * * // log
> * * * * * * * * // do action
> * * * * * * * * return
> * * * * }
>
> * * * * // no match
> * * * * throw e;
> }
> }
Have a look at this thread on a neighboring newsgroup, where a very
similar question was asked. Pretty much all answers there are
applicable to your case as well:
http://groups.google.com/group/micro...b326f3bd849fbb
Note that the code there in VB, and the C# version is more terse
because you can just use anonymous delegates / lambdas.
Something that's probably worth re-iterating: rethrowing exceptions is
not so good in general, but if you do so, at least use "throw;" rather
than "throw ex;", because the former preserves the original stack
trace of the exception.