Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throw a C# exception of the same type as that caught?

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);
     }
  }
like image 810
Black Light Avatar asked Oct 05 '10 12:10

Black Light


People also ask

What does throw () mean in C++?

A throw() specification on a function declaration indicates which specific exception(s) the function is allowed to throw to the caller.

Does C have Throw?

C doesn't support exception handling. To throw an exception in C, you need to use something platform specific such as Win32's structured exception handling -- but to give any help with that, we'll need to know the platform you care about. ...and don't use Win32 structured exception handling.

What happens when you throw C#?

In c#, the throw is a keyword, and it is useful to throw an exception manually during the execution of the program, and we can handle those thrown exceptions using try-catch blocks based on our requirements. The throw keyword will raise only the exceptions that are derived from the Exception base class.

What is throw exception in C#?

Exceptions are used to indicate that an error has occurred while running the program. Exception objects that describe an error are created and then thrown with the throw keyword. The runtime then searches for the most compatible exception handler.


4 Answers

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 CreateInstance overload you're using copy all fields from the innerException to your new outer exception? What if an exception handler higher up the stack depends on parsing the Message property? 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.

like image 141
snemarch Avatar answered Nov 05 '22 08:11

snemarch


all exceptions have a Data property that you can add additional data to. There is no need to create a new exception. Just catch the existing exception and add your information and then just rethrow the exception.

This way you get your cake and eat it too. :)

http://msdn.microsoft.com/en-us/library/system.exception_members(v=VS.90).aspx

like image 35
Khalid Abuhakmeh Avatar answered Nov 05 '22 09:11

Khalid Abuhakmeh


I think you should create your own custom exception type. What kind of information are you going to add? How is the catcher of the exception going to know it has extra information? If you use a custom type, they will have extra properties/methods to view or call.

like image 43
Bryan Avatar answered Nov 05 '22 09:11

Bryan


Don't catch it at all and just let it bubble up - there's no point reinventing the wheel.

Not only is your method not intuitive for somebody else coming in, but you're also going to lose the original stack trace from the first exception.

like image 33
Paddy Avatar answered Nov 05 '22 08:11

Paddy