Java 中 try catch 块中变量“范围”的问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2854144/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Problem with "scopes" of variables in try catch blocks in Java
提问by devoured elysium
Could anyone explain me why in the last lines, br is not recognized as variable? I've even tried putting br in the try clause
, setting it as final
, etc. Does this have anything to do with Java not support closures? I am 99% confident similar code would work in C#.
谁能解释一下为什么在最后几行中, br 不被识别为变量?我什至尝试将 br 放入try clause
,将其设置为final
等。这与 Java 不支持闭包有关吗?我 99% 有信心类似的代码可以在 C# 中工作。
private void loadCommands(String fileName) {
try {
final BufferedReader br = new BufferedReader(new FileReader(fileName));
while (br.ready()) {
actionList.add(CommandFactory.GetCommandFromText(this, br.readLine()));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) br.close(); //<-- This gives error. It doesn't
// know the br variable.
}
}
Thanks
谢谢
采纳答案by Artefacto
Because it's declared in the try block. Local variables are declared in one block are inaccessible in other blocks except if contained in it, i.e., the variables go out of scope when their block ends. Do this:
因为它是在 try 块中声明的。在一个块中声明的局部变量在其他块中是不可访问的,除非包含在其中,即当它们的块结束时变量超出范围。做这个:
private void loadCommands(String fileName) {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(fileName));
while (br.ready()) {
actionList.add(CommandFactory.GetCommandFromText(this, br.readLine()));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) try { br.close(); } catch (IOException logOrIgnore) {}
}
}
回答by ZZ Coder
br is defined in the try block so it's not in the scope in finally block.
br 是在 try 块中定义的,因此它不在 finally 块的范围内。
Define br outside of the try block.
在 try 块之外定义 br。
回答by Jet_C
To update this answer since Java 7 & 8 release:
自 Java 7 & 8 发布以来更新此答案:
Firstly, If you declare a variable inside a traditional try{} block you won't have access to that variable outside of that try block.
首先,如果您在传统的 try{} 块内声明一个变量,您将无法访问该 try 块之外的该变量。
Now since Java 7 you can create a Try-With-Resourceswhich can shorten your code written, it removes your "scope" problem and it also automatically closes resources for you!!! A Hat Trick in this situation ;)
现在,从 Java 7 开始,您可以创建一个Try-With-Resources来缩短您编写的代码,它消除了您的“范围”问题,并且还会自动为您关闭资源!!!在这种情况下的帽子戏法;)
The equivalent code with Try-With-Resourcesis:
Try-With-Resources的等效代码是:
private void loadCommands(String fileName) {
try (BufferedReader br = new BufferedReader(new FileReader(fileName))){
while (br.ready()) {
actionList.add(CommandFactory.GetCommandFromText(this, br.readLine()));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Notice that now you don't even need to worry about the scope of the variable since there is no need to call .close() it is being automatically done for you!
请注意,现在您甚至不需要担心变量的范围,因为不需要调用 .close() 它会自动为您完成!
Any class that implements the AutoClosable interface can be used in a Try-With-Resources block. As a quick example I'll leave this here:
任何实现 AutoClosable 接口的类都可以在 Try-With-Resources 块中使用。作为一个简单的例子,我将把它留在这里:
public class Test implements AutoCloseable {
public static void main(String[] args) {
try (Test t = new Test()) {
throw new RuntimeException();
} catch (RuntimeException e) {
System.out.println(e);
} catch (Exception e) {
System.out.println(e);
}
System.out.println("The exception was caught and the program continues! :)");
}
@Override
public void close() throws Exception {
// TODO Auto-generated method stub
}
}
If you need more explanation on using try-with-resources click here
如果您需要有关使用 try-with-resources 的更多说明,请单击此处