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?
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 matchingcatch
clause is located, the exception propagation is completed by transferring control to the block of thatcatch
clause.
Here the "completed" part indicates that after control has been transferred, that's the end of the special handling, effectively.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With