[英]Java catch different exceptions
public class ExceptionHandler {
public static void main(String[] args) throws FileNotFoundException, IOException {
// write your code here
try {
testException(-5);
testException(11);
} catch (FileNotFoundException e){
System.out.println("No File Found");
} catch (IOException e){
System.out.println("IO Error occurred");
} finally { //The finally block always executes when the try block exits.
System.out.println("Releasing resources");
testException(15);
}
}
public static void testException(int i) throws FileNotFoundException, IOException {
if (i < 0) {
FileNotFoundException myException = new FileNotFoundException();
throw myException;
}
else if (i > 10) {
throw new IOException();
}
}
}
此代码的输出给出
No File Found Releasing resources
java是否可以同时捕获IOException和FileNotFoundException? 它似乎只能捕获第一个异常,而不能捕获IOException
try
块在引发的第一个异常处停止,因此永远不会执行第二次调用testException()
。
您应该将try/catch/finally
块包含在另一个try/catch
块中,因为您的finally
块会抛出必须捕获的异常。
这是您的代码的工作方式:
testException(-5)
抛出FileNotFoundException
FileNotFoundException
被catch (FileNotFoundException e)
No File Found
被打印到标准输出中 finally
执行块(不执行testException(10)
语句)。 Releasing resources
testException(15)
并抛出一个IOException
,但该IOException
始终无法捕获(程序将被中断)。 如果从main
方法中删除throws FileNotFoundException, IOException
,则编译器将警告您未捕获异常( finally
块中的异常)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.