[英]Catch handler for multiple exceptions?
我正在试验异常,我想问一问何时可以在一个处理程序中处理多个异常,什么时候不可以?
例如,我编写了以下代码,该代码结合了两个异常( 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
}
如果这样做,请注意子类必须排在最前面。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.