Order catch blocks when try to handle an exception

前端 未结 5 1064
你的背包
你的背包 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.

提交回复
热议问题