Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throw statement with no arguments, outside catch block in a common exception handler

I have a common exception handler function:

public static void ManageException(Exception ex,
                                   string customErrorMsg,
                                   bool displayMessage)

which I want to call from some of the catch blocks.

After processing the exception, I want to rethrow the exception, while preserving the stack trace.

I read somewhere that I should throw statement without any parameters. The throw statement (without any params) works fine in a catch block, but in my ManageException function, it gives me a compile error:

A throw statement with no arguments is not allowed outside of a catch clause

Is there any solution to re-throw the exception with the whole stack trace and without any performance impact, from the ManageException function?

I am using C# 2.0.

like image 736
AllSolutions Avatar asked Jan 01 '13 18:01

AllSolutions


1 Answers

You have to specify the exception to throw, as in:

throw ex;

As stated in your error, you can only re-throw exceptions (with throw;) from inside a catch block. IMHO this is really the only place it makes sense to do so as well; you are either catching the exception, or throwing it, and probably should not do both. From a method called ManageException, I wonder why you would be managing said exception, but throwing it anyway.

Perhaps you instead want to wrap the original exception in one of your own, providing additional details? In this case I would throw a new exception with ex as the InnerException, if you want to preserve that data.


From your comment, if what you are trying to do is determine whether you should re-throw an exception or not, I would suggest:

  • Rename your method to TryManageException and change the signature to return a bool - return a false if the exception was not managed properly and needs to be re-thrown; return a true if it was handled.
  • If the method returns a false (= not managed), re-throw from the catch block or do whatever else you need:

    try
    {
        decimal oops = 5 / 0;
    }
    catch (Exception e)
    {
        if (!CommonExceptionHandler.TryManageException(e, "oops", "oops"))
            throw;
    }
    
like image 166
lc. Avatar answered Oct 27 '22 00:10

lc.