Is catching 'expected' exceptions that bad? I had to find the corresponding process for a windows service the other day, and I kept on getting this one exception. I've spent some time researching the exception only to find that this exception will occur if the process is terminating, Hence my question, is it really that bad to catch expected exceptions ?

Sample Code:

try
{
  if (proc.MainModule.FileName == controller.ImagePath)
    {
             //Logic goes here
    }
 }
 catch (System.ComponentModel.Win32Exception ex)
 {
      // Thrown if process is already terminating,
      // the process is a Win16 exe or the process
      // could not be accessed.
      MyLogger.Debug(
                   "The following Win32Exception occurred while trying to access the MainModule information: " + ex.ToString());
}
There are some exceptions I classify as "exogenous" exceptions. That is, they are exceptions that state "the world is not how you assumed it would be, and we can't do the thing you asked". The problem with exogenous exceptions is that the world is constantly changing. You think you're going to be able to access that file, and then someone changes its permissions from another process, or the tape drive catches on fire, or someone unplugs the router, or whatever, and oops, you can't access the file after all.

Exogenous exceptions are precisely the ones you should be catching; they indicate situations that are rare enough and dangerous enough to reasonably be exceptions, but common enough that you can have some clue ahead of time as to what they are, and reasonably recover from them.

The other class of exceptions you need to catch are the "vexing" exceptions. That is, the exceptions where someone wrote you a library that communicates with you via exceptions in non-exceptional circumstances. Ideally you should never write a library that requires the developer to catch a vexing exception; rather, expose tools that allow them to prevent the exception.

For example, suppose you write a method that turns a string into an int. You might say

public static int Parse(string s) { ... }


And if the string is malformed, it throws an exception. That is vexing! The developer might have a string where they don't know whether it is well-formed or not, because a user typed it in. The work they have to do to avoid the exception is equivalent to simply not calling the method in the first place. A better way to do it is:

public static bool IsWellFormedIntString(string s) { ... }
public static int Parse(string s) { ... }


or

public static int? Parse(string s) { ... }


or

public static bool TryParse(string s, out int result) { ... }


Or whatever; there are lots of ways to avoid the vexing exception situation.

More thoughts on this topic here:

http://blogs.msdn.com/b/ericlippert/archive/2008/09/10/vexing-exceptions.aspx