提问者:小点点

Java Try/Catch语句异常类型


如果我有一个try/catch块,它捕获IndexOutOfBounds异常,但在同一代码中,我想访问一个文件,是否可以执行一个也能捕获IOException的一般异常?

通常,当我使用try/catch时,我只是放入异常类型,但我以前从未尝试过。 这样做是不对的,还是只是不好的做法?

try {
    // code to access a File which does not exist and inserts into an array index which does not exist
} catch (Exception eitherException){
    // prints "An exception happened"
}

我需要嵌套块,多个catch子句吗? 我在网上研究了一段时间,但找不到答案。 谢谢!


共1个答案

匿名用户

您编写的代码也将捕获IOException,因为Exception类是所有异常的父类。 它将捕获所有类型的异常。 如果您不想捕获所有异常,并且只捕获这两个异常,您可以这样编写。

try {
// code to access a File which does not exist and inserts into an array index which does not exist
} catch (IndexOutOfBounds | IOException  eitherException){
// prints "An exception happened"
}