How often should I use try and catch in C#?

This is a big topic. Start here for some excellent discussion of Exception handling best practices and be prepared for a religious war...

Code Analysis Team Blog

Martin Fowler - Fail Fast

MSDN on Exception Handling

Checked vs Unchecked Exceptions

My own opinion is that for the most part you use "try/finally" a lot, but "catch" very little. The problem is that if you attempt to catch and handle Exceptions in the wrong instances, you may inadvertently put your application in a bad state. As a rule, use dev and test to learn where you actually need to handle an exception. Those will be places that you can't check. i.e. you shouldn't really need to handle nullreference or filenotfound because you can proactively check for those. Only exceptions you know may happen, but you can't do anything about. Beyond that, for the sake of your data's state, let it crash.

If you are swallowing exceptions, it generally means you don't understand your program or why you are getting an exception. Catching System.Exception is the poster child of code smells...


The only down side is when an exception is actually thrown. There is no overhead for wrapping the code, except for when exceptions occur.

Also, you don't want to use try/catch for control flow. Consider this (bad code):

try {

    FileStream fs = File.Open("somefile.txt", FileMode.Open);

} catch (Exception ex) {
    MessageBox.Show("The file does not exist. Please select another file");
}

You'll get more performance from some thing like File.Exists. such as:

if(!File.Exists("somefile.txt"))
  MessageBox.Show("The file does not exist.")

EDIT: found the MSDN direct quote:

Finding and designing away exception-heavy code can result in a decent perf win. Bear in mind that this has nothing to do with try/catch blocks: you only incur the cost when the actual exception is thrown. You can use as many try/catch blocks as you want. Using exceptions gratuitously is where you lose performance. For example, you should stay away from things like using exceptions for control flow.


Actually, I very rarely use a catch block except for logging purposes. finally is much more common for me. Most times, lock or using do everything I can usefully do (and indeed, that is a finally also).

Eric Lippert has a blog entry on exceptions that may be useful.

Tags:

C#