Exceptions to Never Catch
Asked Answered
T

4

5

I know that there are some exception types that cannot be caught in catch blocks, like StackOverflowException in .NET 2.0. I would like to know which other exceptions are inadvisable to catch, or are associated with bad practices.

The way I would like to use this list of exception types is to check it every time I am using Exception in a catch block:

private static readonly Type[] _exceptionsToNotCatch = new Type[] { typeof(StackOverflowException) };

// This should never throw, but should not swallow exceptions that should never be handled.
public void TryPerformOperation()
{
    try
    {
        this.SomeMethodThatMightThrow();
    }
    catch (Exception ex)
    {
        if (_exceptionsToNotCatch.Contains(ex.GetType()))
            throw;
    }
}

EDIT

I don't think I provided a very good example. That's one of the problems with trying to make an example trivial when trying to communicate one's meaning.

I never throw Exception myself, and I always catch specific exceptions, only catching Exception as follows:

try
{
    this.SomeMethodThatMightThrow();
}
catch (SomeException ex)
{
    // This is safe to ignore.
}
catch (Exception ex)
{
    // Could be some kind of system or framework exception, so don't handle.
    throw;
}

My question was meant as more of an academic one. What exceptions are only thrown by the system and should never be caught? I am worried about situations more like this:

try
{
    this.SomeMethodThatMightThrow();
}
catch (OutOfMemoryException ex)
{
    // I would be crazy to handle this!
    // What other exceptions should never be handled?
}
catch (Exception ex)
{
    // Could be some kind of system or framework exception, so don't handle.
    throw;
}

This question was really inspired by the following: System.Data.EntityUtil.IsCatchableExceptionType(Exception) in System.Data.Entity, Version=3.5.0.0

Trochanter answered 22/9, 2013 at 22:15 Comment(4)
I think the real solution is to not catch Exception. Catch exceptions that you are prepared to deal with. It's often better to let an exception go than to swallow it if you have no real recourse for it.Wrench
Second what @MattGreer was saying. What you're setting out to do is the opposite of how you should handle exceptions. Catch and deal with the exceptions you might expect. If stuff falls through and crashes your app, it means you need to make your exception handling more robust. This doesn't add that robustness.Doggo
I'm a bit confused by the question (even though the answer given below is perfect). Are you asking what you shouldn't catch? Or what you can't catch? Because you start off by giving an example of what can't be caught.. yet you finish with what isn't "advisable".Middleton
Maybe you could find this interesting.Doublecheck
J
19

I would like to know which other exceptions are inadvisable to catch, or are associated with bad practices.

Here is the list of all exceptions you shouldn't catch:

  1. Any exception you don't know what to do with

Here's the best practice for exception handling:

If you don't know what to do with an exception, don't catch it.

This may sound snarky, but they're both correct, and that's all you need to know.

Jocular answered 22/9, 2013 at 22:19 Comment(10)
Right on the money. +1Doggo
can I get more explanation on the reasons why wu shouldn't catch it?Rajasthan
@patxy: Sure, what are you going to do with that exception you just caught?Jocular
right, it's better to throw an exception than add an empty catchPlight
I don't know, that's the reason why I asked. Usually, I log all the exceptions, and sometimes, I display a message for the userRajasthan
@patxy: Log the exception that takes down your application, sure, of course. But let it go. Once you know the code that's throwing, and why it is throwing, you can design strategies to mitigate these exceptions. You now know what to do with the exception, and so may now catch it.Jocular
This is not always what you want. E.g. if an IDE plugin provided a syntax highlighter, the editor could catch "most" exceptions thrown by the highlighter and respond by disabling syntax highlighting for the remainder of the session. The important question is which exceptions should not be caught under this scenario, which is exactly the question the OP asked. In my work, I refer to this set of exception types as critical exceptions, which I took from ErrorHandler.IsCriticalException().Pledget
Although I couldn't find the post at the time, I was looking for something like https://mcmap.net/q/696125/-which-types-of-exception-not-to-catch. I think your answer really hit home, though - never catch an exception I don't understand.Trochanter
@280Z28 - Yes, this is what I was looking for. It's too bad I screwed up my post with a bad example. Thanks.Trochanter
@Trochanter It is ironically that simple. Otherwise, you risk your application getting into an indeterminate state. Better to learn what can go wrong than assume everything is okay. Cheers.Jocular
D
2

Using Exception in the catch block would catch all exceptions that are catchable. I would say you should specify only exceptions that needs to be caught and let the ones you don't want to catch spill out. E.g.

try
{

}
catch(SqlException sqlex)  //specific to database calls
{
   //do something with ex
}
catch(FormatException fex) //specific to invalid conversion to date, int, etc
{
   //do something with ex
}
catch(Exception ex)
{
    //I didn't know this exception would be thrown
    //log it for me or Rethrow it
}

Any other exception not in that list will not be caught

Dulcy answered 22/9, 2013 at 22:23 Comment(0)
B
2

It's generally not a good idea to do that.

You should catch the most specific exception(s) possible and only carry on execution of your program when it is safe to do so. E.g. if you're opening a file, it's perfectly reasonable to catch exceptions relating to file access / permission errors, but probably not much else. You certainly wouldn't want to catch an OutOfMemoryException and then blindly carry on. They're very different errors!

If you apply a blanket rule of what to catch, there's no guarantee that your program will be able to continue execution safely because you're not responding to specific situations, just applying a one size does not fit all solution.

Bulwark answered 22/9, 2013 at 22:27 Comment(0)
B
1

Okay so we've established it ain't a good idea. And we've established that programmers on SO prefer to opine from their high-horses rather than hand you a knife to stab yourself with, so for those with suicidal tendencies, let's start with these:

(Redacted my list and DRYing-up SO to point to Hans' list)

https://mcmap.net/q/696125/-which-types-of-exception-not-to-catch

Bybee answered 25/10, 2017 at 17:42 Comment(1)
@HansPassant pointed me to his great answer on another question, so I'll update this answer to point to that one. https://mcmap.net/q/696125/-which-types-of-exception-not-to-catchBybee

© 2022 - 2024 — McMap. All rights reserved.