Hi,
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);
}
}