【发布时间】:2014-04-23 16:14:42
【问题描述】:
我注意到当以下变量在 try { } 中时,我无法对它们使用 finally 方法,例如:
import java.io.*;
public class Main
{
public static void main() throws FileNotFoundException
{
try {
File src = new File("src.txt");
File des = new File("des.txt");
/*code*/
}
finally {
try {
/*closing code*/
System.out.print("After closing files:Size of src.txt:"+src.length()+" Bytes\t");
System.out.println("Size of des.txt:"+des.length()+" Bytes");
} catch (IOException io){
System.out.println("Error while closing Files:"+io.toString());
}
}
}
}
但是当声明在main()之前放在try{}之前,程序编译没有错误,
有人可以指出我的解决方案/答案/解决方法吗?
【问题讨论】:
-
when the declarations where placed in main() before Try{ }这就是解决方案。在更大的范围内声明变量。 -
没有变通办法。这是 java 中的预期行为。变量范围很严格。
-
如果您在块内声明了任何变量,例如
{或},那么它就无法在作用域外访问。
标签: java try-catch block scope finally