17

Consider the following:

try { FileStream fileStream = new FileStream("C:\files\file1.txt", FileMode.Append); } catch (DirectoryNotFoundException e) { MessageBox.Show("Directory not found. " + e.Message); } catch (IOException e) { MessageBox.Show("Other IO Error. " + e.Message); } catch (Exception e) { MessageBox.Show("Other Error. " + e.Message); } 

Will a DirectoryNotFoundException exception get handled by all three catch clauses or just the first one?

5 Answers 5

27

Just the first one. The exception doesn't propagate to all matching catch clauses.

From the C# 4 spec, section 8.9.5:

The first catch clauses that specifies the exception type or a base type of the exception type is considered a match. [...] If a matching catch clause is located, the exception propagation is completed by transferring control to the block of that catch clause.

Here the "completed" part indicates that after control has been transferred, that's the end of the special handling, effectively.

Sign up to request clarification or add additional context in comments.

Comments

3

Only the first one. Catch-blocks doesn't fall through.

Comments

3

Only the first matching catch catches the exception, should you for any reason need to cacth it again you will have to throw it again so the "external" catch caluses will be able to catch it.

Comments

1

only the 1st one , the 1st matching catch clause will handle the exception

Comments

1

This is the correct way to handle exceptions - start with the most specific exception type and work back. Bare in mind however, if you can't do anything to resolve or handle an exception, don't catch it. For example, I'm assuming your code is in some file-access method, I would remove the last catch (Exception) block, as there's nothing you can do about it here (what if it's a stack overflow, out of memory or some other serious system exception...)

2 Comments

You should always catch all exceptions, because the user should never see the generic display of the exception with the stack trace etc.
No, not always. The most generic exceptions should only be caught at the very top of the presentation layer, since this is the only place you can do anything about them (display a nice error message).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.