我正在尝试异常,我想问一下什么时候可以在一个处理程序中处理多个异常,什么时候不能?
例如,我编写了以下代码,它结合了两个异常(FileNotFoundException OutOfMemoryError),并且程序运行正常,没有任何错误。 Al 认为处理与代码的功能不太相关,我选择它们只是为了看看何时可以在处理程序中组合多个异常:
import java.io.FileNotFoundException;
import java.lang.OutOfMemoryError;
public class exceptionTest {
public static void main(String[] args) throws Exception {
int help = 5;
try {
foo(help);
} catch (FileNotFoundException | OutOfMemoryError e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static boolean foo(int var) throws Exception {
if (var > 6)
throw new Exception("You variable bigger than 6");
else
return true;
}
}
但是当我选择不同类型的异常时,编译器会给出错误。例如,当我选择 IOException 和 Exception 时,出现错误:异常已处理”:
import java.io.IOException;
import java.lang.Exception;
public class exceptionTest {
public static void main(String[] args) throws Exception {
int help = 5;
try {
foo(help);
} catch (IOException | Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static boolean foo(int var) throws Exception {
if (var > 6)
throw new Exception("You variable bigger than 6");
else
return true;
}
}
那么为什么会发生这种情况呢?为什么在一种情况下我可以在处理程序中使用多个异常,而在另一种情况下则不能?预先感谢您。
最佳答案
您收到该消息是因为 IOException
是 Exception
的子类。因此,如果抛出 IOException
,它将被 catch (Exception e)
语句捕获,因此将其捕获为 IOException
是多余的.
第一个示例之所以有效,是因为 FileNotFoundException
和 OutOfMemoryError
都不是对方的子类。
但是,您可以使用单独的 catch 语句捕获子类异常:
try{
// code that might throw IOException or another Exception
} catch (IOException e) {
// code here will execute if an IOException is thrown
} catch (Exception e) {
// code here will execute with an Exception that is not an IOException
}
如果您这样做,请注意子类必须放在第一位。
关于java - 捕获多个异常的处理程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24233659/