开发者

C#: multiple catch clauses

Consider the foll开发者_运维百科owing:

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 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.


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


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.


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


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...)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜