考虑以下几点:
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); }
DirectoryNotFoundException
异常是由所有三个 catch
子句处理还是仅由第一个子句处理?
最佳答案
只是第一个。异常不会传播到所有 匹配的 catch 子句。
来自 C# 4 规范,第 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.
这里的“完成”部分表示控制权转移后,特殊处理结束,有效。
关于C#:多个 catch 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5375437/