class Demo
{
public static void main(String args[]) throws java.io.IOException
{
try(FileInputStream fin = new FileInputStream("Demo.txt"))
{
//This block is executed successfully
}
System.out.println("Will it be executed if error occurs in try clause");
}
}
假设try block
中的代码如代码中所述成功执行,而exception
中出现了try with resource clause
,这意味着auto closing
文件中出现异常。
try with resource clause
中的异常?我想问的是,该异常会被抛到JVM并且会突然终止我的程序并且println
语句不会被执行吗?
我可以捕获该异常,以便还可以执行剩余的程序吗?
答案 0 :(得分:6)
如果close
的{{1}}方法抛出异常,则在AutoClosable
块执行后确实会抛出异常。
如果需要处理异常,只需在try子句中添加一个catch子句即可。
以下代码说明了行为:
try
它使用堆栈跟踪终止JVM:
public class Foo {
public static class Bar implements AutoCloseable {
@Override
public void close() {
throw new RuntimeException();
}
}
public static void main(String args[]) {
try (Bar b = new Bar()) {
// This block is executed successfully
}
System.out.println("Will it be executed if error occurs in try clause");
}
}
25是我的Exception in thread "main" java.lang.RuntimeException
at test3.Foo$Bar.close(Foo.java:14)
at test3.Foo.main(Foo.java:25)
子句的结束}
所在的行。
可以使用以下方式处理:
try
答案 1 :(得分:4)
只添加catch子句,以捕获异常,否则程序将被终止
public static void main(String[] args) throws FileNotFoundException, IOException {
try(FileInputStream fin = new FileInputStream("Demo.txt"))
{
//This block is executed successfully
}
catch(Exception e)
{
e.printStackTrace();
}
System.out.println("Will it be executed if error occurs in try clause");
}
答案 2 :(得分:1)
我认为最后程序的其余部分将会运行,请尝试并报告。
课程演示
{
public static void main(String args[]) throws java.io.IOException
{
try(FileInputStream fin = new FileInputStream("Demo.txt"))
{
//This block is executed successfully
} finally {
System.out.println("Will it be executed if error occurs in try clause");
}
}
}
答案 3 :(得分:1)
只需删除文件Demo.txt并运行以下代码。
抛出此类异常的最简单方法是运行此代码,没有现有资源(在本例中为Demo.txt):
public static void main(String args[])
{
try(FileInputStream fin = new FileInputStream("Demo.txt"))
{
} catch(IOException exc) {
System.out.println("An exception has occured. Possibly, the file does not exist. " + exc);
}
System.out.println("Will it be executed if error occurs in try clause");
}