3

Lets say I need to run methodA and methodA will throw a FormatException.

If I write this block:

try
{
    methodA();
}
catch (Exception ex)
{
    methodB();
}
catch (FormatException ex)
{
    methodC();
}

Will it ever run methodC, knowing that FormatException is also an Exception and therefor will go into the catchblock of methodB.

Or is it better to write it like this:

try
{
    methodA();
}
catch (Exception ex)
{
    if(ex is FormatException)
    {
        methodC();
    } else
    {
        methodB();
    }
}
MethodMan
  • 18,625
  • 6
  • 34
  • 52
Edito
  • 3,030
  • 13
  • 35
  • 67
  • 3
    Order matters when catching exceptions. – juharr Sep 14 '15 at 16:39
  • 2
    You're first example is better but the order of your catch blocks should always go Most Specific to Least Specific. Therefore, the last catch block should catch Exception. – rmn36 Sep 14 '15 at 16:40
  • The second method you suggest is best. [Here's an example](http://stackoverflow.com/questions/136035/catch-multiple-exceptions-at-once) of a similar question. – TestWell Sep 14 '15 at 16:40
  • 1
    @TestWell Not if you do different things for each type of exception. – juharr Sep 14 '15 at 16:41
  • 1
    @TestWell It is completely unnecessary to catch a generic exception and then test for type. – Dave Zych Sep 14 '15 at 16:41

2 Answers2

10

No, it won't ever run methodC, but if you swap the order of your catch's it will:

try
{
    methodA();
}
catch (FormatException ex)
{
    methodC();    
}
catch (Exception ex)
{
    methodB();
}

To quote MSDN:

It is possible to use more than one specific catch clause in the same try-catch statement. In this case, the order of the catch clauses is important because the catch clauses are examined in order. Catch the more specific exceptions before the less specific ones. The compiler produces an error if you order your catch blocks so that a later block can never be reached.

Dave Zych
  • 21,581
  • 7
  • 51
  • 66
1

The catch block are always executed according to specific exception.

All the Exceptions are derived from System.Exception class so it should be in the last of your catch blocks.

All other catch blocks should of a specific Exception class (FormatException in your case) that you presumed, could be invoked by your method.

Dave's Answer is a perfect example for it and also if Exceptions in your catch blocks have some hierarchical relation then better reorder them in a reverse hierarchical order.

Manish Singh
  • 360
  • 1
  • 6
  • 18