Reviewing catch blocks

Here’s an interesting exercise. If you’re writing code in a language like C# or C++ that has catch statements, write a script to report all catch blocks. You might be surprised at what you find. Some questions to ask:

  • Do catch blocks swallow exceptions and thus mask problems?
  • Is information lost by catching an exception and throwing a new one?
  • Are exceptions logged appropriately?
  • Are notification messages grammatically correct and helpful?

Here’s a PowerShell script that will report all catch statements plus the five lines following the catch statement.

Related post: Finding embarrassing and unhelpful error messages

2 thoughts on “Reviewing catch blocks

  1. Ohhhh, I used to get Really Irritated when I used packages (such as IBM’s DB2java) that seemed to wrap everything in this:
    try {

    } catch (Exception x) {
    throw new MyEffingException(x.toString());
    }

    You lost the original stack trace, and could often not figure out what was wrong. At least current versions of Java allow you to imbed the original exception inside the new one that you’re throwing, so nothing’s lost. But, really, why?

    In Java, this is often done through laziness. It’s easier to declare you procedure with “throws MyEffingException” than to enumerate all the exceptions you might wind up throwing. (Of course, if you’re doing that, you might as well just say “throws Exception”, and have done with it; you’re not adding anything with this silliness.)

    My opinion is that in any language you should only catch exceptions in three cases:
    1. Certain “exceptions” actually represent expected situations that you need to handle, such as end of data.
    2. You think you can do reasonable recovery from certain exceptions, such as numeric overflow or file not found.
    3. You’re running something like a server loop, and you don’t want an exception in one iteration to kill the server, so you catch everything inside the loop.

    In cases 1 and 2, you should only be catching the specific exceptions that you can handle or recover from. In all three cases, you should be logging the details of the exception you caught, regardless of the outcome.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>