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
答案 0 :(得分:3)
try
块在抛出的第一个异常处停止,因此永远不会执行testException()
的第二次调用。
答案 1 :(得分:2)
您应该将try/catch/finally
块放在另一个try/catch
块中,因为您的finally
块可能会抛出必须捕获的异常。
以下是您的代码的工作原理:
testException(-5)
会抛出FileNotFoundException
FileNotFoundException
被catch (FileNotFoundException e)
抓取
No File Found
打印在标准输出finally
阻止(不执行testException(10)
句子。)Releasing resources
testException(15)
并抛出一个未被捕获的IOException
(程序将被中断)。如果从throws FileNotFoundException, IOException
方法中删除main
,编译器将提醒您未捕获异常(finally
块中的异常)。