R
RedLars
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;
}
}
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;
}
}