gpt4 book ai didi

java - 为什么我不能访问 try/catch block 中的变量?

转载 作者:塔克拉玛干 更新时间:2023-11-01 23:10:10 25 4
gpt4 key购买 nike

假设我有以下代码:

try {
Reader reader = new FileReader("/my/file/location");
//Read the file and do stuff
} catch(IOException e) {
e.printStackTrace();
} finally {
reader.close();
}

为什么reader只存在于try括号内?这是为了阻止在对象 reader 尚未初始化或设置的代码中较早抛出的 Exception 吗?

我应该如何清理存在于 try 子句中的对象,还是必须将它们带到外面?

最佳答案

你必须把它们放在外面,否则变量只存在于 try block 中。但这是一个改进。如果您将代码更改为:

Reader reader = new FileReader("/my/file/location");
try {
//Read the file and do stuff
} catch(IOException e) {
e.printStackTrace();
} finally {
reader.close();
}

那么try-block中的代码,包括finally,都可以依赖reader创建成功。否则,在您的示例中,如果实例化失败,您的代码仍会尝试在退出时关闭仍然为空的读取器。

在这个改变的例子中,读取器实例化抛出的异常没有被 catch block 处理。

问题的组合导致您来到这里,一个是您更担心尝试用一个 catch block 压缩所有异常,而不是在开始调用读取器上的方法之前确保读取器处于有效状态。 (你会在 JDBC 代码中看到很多这种 one-try-block-to-rule-them-all 的风格,人们就是不忍心写所有嵌套的 try block ,它太丑了,无法容忍。)另外,它是像这样在本地捕获所有异常的非常玩具示例,在现实生活中,如果出现问题,你想让异常被抛出,以便应用程序的其余部分可以知道出现问题,给你类似的东西

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);
}
}
}

这与 try-with-resources 的作用非常相似。 try-with-resources 首先创建对象,然后执行 try block ,然后关闭它创建的东西,确保关闭时抛出的任何异常都不会掩盖 try block 中抛出的异常。创建对象仍然有可能引发异常,它不会被 try-with-resources 处理。

public void doStuffWithFile() throws IOException {
try (Reader reader = new FileReader("/my/file/location")) {
//Read the file and do stuff
}
}

关于java - 为什么我不能访问 try/catch block 中的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31993167/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com