Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

try
{
    // throws IOException
}
catch(Exception e)
{
}
catch(IOException e)
{
}

when try block throws IOException, it will call the first catch block, not the second one. Can anyone explain this? Why does it call the first catch block?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
613 views
Welcome To Ask or Share your Answers For Others

1 Answer

From try-catch (C# Reference);

It is possible to use more than one specific catch clause in the same try-catch statement. In this case, the order of the catch clauses is important because the catch clauses are examined in order. Catch the more specific exceptions before the less specific ones. The compiler produces an error if you order your catch blocks so that a later block can never be reached.

You should use

try
{
    // throws IOException
}
catch(IOException e)
{
}
catch(Exception e)
{
}

Be aware, Exception class is the base class for all exceptions.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...