简体   繁体   English

尝试处理异常时对 catch 块进行排序

[英]Order catch blocks when try to handle an exception

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.try块抛出IOException ,它将调用第一个catch块,而不是第二个。 Can anyone explain this?谁能解释一下? Why does it call the first catch block?为什么它调用第一个catch块?

From try-catch (C# Reference) ;来自try-catch(C# 参考)

It is possible to use more than one specific catch clause in the same try-catch statement.在同一个 try-catch 语句中可以使用多个特定的 catch 子句。 In this case, the order of the catch clauses is important because the catch clauses are examined in order.在这种情况下,catch 子句的顺序很重要,因为 catch 子句是按顺序检查的。 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.如果您对 catch 块进行排序以便永远无法到达后面的块,则编译器会产生错误。

You should use你应该使用

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

Be aware, Exception class is the base class for all exceptions.请注意, Exception类是所有异常的基类。

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.因此,无论何时抛出任何类型的异常,它都会首先被第一个可以捕获任何类型的异常的 catch 块捕获。

So try using IOCException before the Exception所以尝试在Exception之前使用IOCException

You can see the hierarchy of IOCException here您可以在此处查看 IOCException 的层次结构

They are catched in the order you specify.它们按您指定的顺序捕获。 In your case you should put IOException above Exception .在您的情况下,您应该将IOException放在Exception之上。 Always keep Exception as last.始终将Exception作为最后。

原因是IOException派生自Exception ,所以IOException实际上一个Exception (" is-a "),因此第一个catch处理程序匹配并被输入。

IOException inherits from Exception. IOException 继承自 Exception。 All Exceptions do.所有异常都可以。 When you catch Exception first, you will catch all exceptions (including IOException).当您首先捕获 Exception 时,您将捕获所有异常(包括 IOException)。 Make sure that your catch(Exception e) is the last catch in the list otherwise all other exception handling will be effectively ignored.确保您的 catch(Exception e) 是列表中的最后一个捕获,否则所有其他异常处理将被有效地忽略。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM