尝试处理exception时命令catch块

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

try块抛出IOException ,它将调用第一个catch块而不是第二个。 任何人都可以解释这一点。 为什么它会调用第一个catch块?

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

可以在同一个try-catch语句中使用多个特定的catch子句。 在这种情况下,catch子句的顺序很重要,因为catch子句按顺序检查。 在不太具体的exception之前捕获更具体的exception。 如果您订购了catch块,编译器会产生错误,以便永远无法访问以后的块。

你应该用

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

请注意, Exception类是所有exception的基类。

exception类是所有exception的基类。 因此,每当抛出任何类型的exception时,它将首先被第一个可以捕获任何类型的exception的catch块捕获。

所以在Exception之前尝试使用IOCException

您可以在此处查看IOCException的层次结构

它们按照您指定的顺序捕获。 在您的情况下,您应该将IOException置于Exception之上。 始终将Exception保留为最后一个。

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

IOExceptioninheritance自Exception。 所有例外都有。 首先捕获Exception时,将捕获所有exception(包括IOException)。 确保catch(exceptione)是列表中的最后一个catch,否则将有效地忽略所有其他exception处理。