Java 多个异常的捕获处理程序?
我正在试验异常,我想问一下,什么时候可以在一个处理程序中处理多个异常,什么时候不可以 例如,我编写了下面的代码,它结合了两个异常(FileNotFoundException OutOfMemoryError),程序运行正常,没有任何错误。Al认为处理与代码的功能不太相关,我选择它们只是为了看看何时可以在on handler中组合多个异常:Java 多个异常的捕获处理程序?,java,exception,error-handling,Java,Exception,Error Handling,我正在试验异常,我想问一下,什么时候可以在一个处理程序中处理多个异常,什么时候不可以 例如,我编写了下面的代码,它结合了两个异常(FileNotFoundException OutOfMemoryError),程序运行正常,没有任何错误。Al认为处理与代码的功能不太相关,我选择它们只是为了看看何时可以在on handler中组合多个异常: import java.io.FileNotFoundException; import java.lang.OutOfMemoryError; publi
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时,我有一个错误,异常已被处理:
那么为什么会发生这种情况呢?为什么在一种情况下我可以在处理程序中使用多个异常,而在另一种情况下我不能使用多个异常呢?提前谢谢你。你收到了这个消息,因为
IOException
是exception
的一个子类。因此,如果抛出IOException
,它将被捕获(异常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
}
如果您这样做,请注意子类必须放在第一位。您有自己的名为
IOException
的类吗?OutOfMemoryError
属于java.lang.Error
层次结构。不同于java.lang.Exception
。看看不同的类:&看看适合我的工作(JDK 1.7)没有警告,没有错误。事实上,这两个都是可丢弃的子类。是的,McLoving,现在我明白了问题的原因。Chris Tarazi已经给了我答案,清楚地解释了这一点:“我认为问题在于IOException是异常的孩子。因此,您没有理由同时处理特定异常(IOException)和广泛异常(exception)。“感谢所有人的评论和兴趣!不客气。处理异常和继承时会有很多复杂问题。
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
}