2

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?

Guenther
  • 403
  • 2
  • 16
  • 1
    Do you mean the `CustomException` *constructor* does all of that work? If so, just move it into a method you can call without throwing an exception. – Jon Skeet Apr 24 '18 at 05:39
  • Create a class that inherits from Exception, and then wherever you need that exception to be handled you throw it to the outer `catch`. [MSDN](https://learn.microsoft.com/en-us/dotnet/standard/exceptions/how-to-create-user-defined-exceptions) – Schalk Apr 24 '18 at 05:41
  • 2
    Why do you throw the CustomException at all? Only for catching it in the next moment? Your CustomException is only for exception handling (logging, mailing, etc.) - pass the original exception to a method that will do so. – Sir Rufo Apr 24 '18 at 05:47
  • Possible duplicate of [How to be explicit about NOT throwing an exception?](https://stackoverflow.com/questions/45839914/how-to-be-explicit-about-not-throwing-an-exception) – Yoh Deadfall Apr 24 '18 at 05:55

1 Answers1

4

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.

Zohar Peled
  • 79,642
  • 10
  • 69
  • 121
  • Thanks, Interesting read, and you are sooooo right! My aim was to sort out all Exceptions, log them, mail them, show custom error messages. Clearly if I do not need an custom exception for this, I do not have to catch it afterwards. – Guenther Apr 24 '18 at 15:39
  • Glad to help :-) – Zohar Peled Apr 24 '18 at 16:14