Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: multiple catch clauses

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?

like image 835
Craig Johnston Avatar asked Mar 21 '11 08:03

Craig Johnston


1 Answers

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.

like image 74
Jon Skeet Avatar answered Oct 13 '22 10:10

Jon Skeet