Search code examples
c#custom-exceptionscustom-error-handling

C# Can a custom exception catch/kill itself?


My code looks like this

var i = 0;
try
{
    i = faultyProcedure();
}
catch (Exception ex)
{
    try
    {
        throw new CustomException("faultyProcedure called", ex);
    }
    catch (CustomException) {}
}

Though it works, it looks silly. The custom exception does all the logging, mailing, etc. even exits the application if necessary.

Is there a way for the custom exception to catch/kill itself, so there is no need for the inner try/catch block?


Solution

  • So... you are using your CustomException to handle other exceptions? If that is the case, then I'm sorry to be the one to tell you, but it doesn't just look silly, it is silly.

    That's not what exceptions are for.

    Exceptions are designed to indicate exceptional situations, mainly things you don't have control over when you write the code, such as IO or network problems.

    To handle exceptions you can write your code into any class, but there is no point of throwing a new exception just to handle an exception that was caught by a catch clause.

    I believe this is an example of a vexing exception:

    Vexing exceptions are the result of unfortunate design decisions. Vexing exceptions are thrown in a completely non-exceptional circumstance, and therefore must be caught and handled all the time.

    The example in Eric Lippert's blog is int.Parse, but I think this code is just as valid as an example of a vexing exception.