Order catch blocks when try to handle an exception

前端 未结 5 1065
你的背包
你的背包 2020-12-19 14:05
try
{
    // throws IOException
}
catch(Exception e)
{
}
catch(IOException e)
{
}

when try block throws IOException, it wi

相关标签:
5条回答
  • 2020-12-19 14:07

    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.

    0 讨论(0)
  • 2020-12-19 14:15

    They are catched in the order you specify. In your case you should put IOException above Exception. Always keep Exception as last.

    0 讨论(0)
  • 2020-12-19 14:20

    IOException inherits from Exception. All Exceptions do. When you catch Exception first, you will catch all exceptions (including IOException). Make sure that your catch(Exception e) is the last catch in the list otherwise all other exception handling will be effectively ignored.

    0 讨论(0)
  • 2020-12-19 14:23

    The reason is that IOException derives from Exception, so IOException actually is an Exception ("is-a") and therefore the first catch handler matches and is being entered.

    0 讨论(0)
  • 2020-12-19 14:24

    Exception class is the base class of all exceptions. So whenever exception is of any type is thrown it will first will be caught by the first catch block which can catch any type of Exception.

    So try using IOCException before the Exception

    You can see the hierarchy of IOCException here

    0 讨论(0)
提交回复
热议问题