why (if at all) is this a bad idea ?
class Program
{
static void Main(string[] args)
{
try
{
throw new NotImplementedException("Oh dear");
}
catch (Exception ex)
{
throw NewException("Whoops", ex);
}
}
// This function is the salient bit here
public static Exception NewException(String message, Exception innerException)
{
return Activator.CreateInstance(innerException.GetType(), message, innerException) as Exception;
}
}
The important bit here is that the function creates an exception of the same type as the “innerException”.
I’m thinking… “Oh… an exception has occurred. I can’t actually handle it here, but I can add some additional information, and re-throw. Maybe another handler, higher up the call chain can handle it.”
A case in point might be some sort of SQL error. I might not be able to handle the exception at the point of calling, but might wish to add some additional “context” information like “I was calling this, and passing that”.
It seems like it might be useful to pass back up the call chain an exception of the type that was originally raised, as opposed to “Exception” or “ApplicationException”. I know I could create my own custom exception classes, but it seems that it adds nothing much when you already have a nice specific exception.
Of course, I might be wrong. It might be a very useful thing to do… but a little voice is suggesting not.
—– edit —–
For the sake of debate, consider the effects of the following two functions (using the code above):
This… seen all too often:
static int SalesTotal(int customerNumber)
{
try
{
throw new DivideByZeroException(); // something you didn't expect
}
catch (Exception ex)
{
throw new ApplicationException("Unable to calculate sales for customer " + customerNumber, ex);
}
}
versus this…
static int SalesTotal(int customerNumber)
{
try
{
throw new DivideByZeroException(); // something you didn't expect
}
catch (Exception ex)
{
throw NewException("Unable to calculate sales for customer " + customerNumber, ex);
}
}
Creating a new exception type isn’t a good option for a general method like this, since existing code will be unable to react to a specific error. (Translation exceptions at API boundaries cane be useful, though).
Creating a new exception of the same type seems perilous. Does the
CreateInstanceoverload you’re using copy all fields from theinnerExceptionto your new outer exception? What if an exception handler higher up the stack depends on parsing theMessageproperty? What if the exception constructor has side effects?IMHO, what you’re really doing is logging, and you’d probably be better off actually doing logging and a re-throw.