ins*_*sin 3 java exception-handling exception try-catch
说我有以下代码:
try {
Reader reader = new FileReader("/my/file/location");
//Read the file and do stuff
} catch(IOException e) {
e.printStackTrace();
} finally {
reader.close();
}
Run Code Online (Sandbox Code Playgroud)
为什么读者只存在于try
括号内?这是为了阻止Exception
在对象reader
尚未初始化或设置的代码中更早抛出该异常吗?
我应该如何清理该try
子句中存在的对象,还是必须将它们带到外部?
您必须将它们带到外面,因为否则变量仅存在于try块中。但这是一个改进。如果将代码更改为此:
Reader reader = new FileReader("/my/file/location");
try {
//Read the file and do stuff
} catch(IOException e) {
e.printStackTrace();
} finally {
reader.close();
}
Run Code Online (Sandbox Code Playgroud)
那么try块中的代码(包括finally)都可以依赖已成功创建的阅读器。否则,在您的示例中,如果实例化失败,您的代码仍将尝试关闭读取器,但该读取器在退出时仍为null。
在此更改后的示例中,catch块无法处理读取器实例化引发的异常。
一系列的问题导致您陷入困境,其中一个问题是:与开始在其上调用方法之前确保阅读器处于有效状态相比,您更担心尝试使用一个catch块压缩所有异常。(您会在JDBC代码中看到很多这种“一试到一遍”的样式,人们无法忍受写所有嵌套的try块,这太丑了以至于无法忍受。)此外,它是可以像这样在本地捕获所有异常的玩具示例,在现实生活中,如果出现问题,您希望引发该异常,以便应用程序的其余部分可以知道出了什么问题,给您类似的东西
public void doStuffWithFile() throws IOException {
Reader reader = new FileReader("/my/file/location");
try {
//Read the file and do stuff
} finally {
try {
reader.close();
} catch (IOException e) {
// handle the exception so it doesn't mask
// anything thrown within the try-block
log.warn("file close failed", e);
}
}
}
Run Code Online (Sandbox Code Playgroud)
这与try-with-resources的功能非常相似。try-with-resources首先创建对象,然后执行try块,然后关闭其创建的对象,确保在close上抛出的任何异常都不会掩盖在try块中抛出的异常。创建对象仍然有可能引发异常,而try-with-resources不会处理它。
public void doStuffWithFile() throws IOException {
try (Reader reader = new FileReader("/my/file/location")) {
//Read the file and do stuff
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4635 次 |
最近记录: |