我注意到,当以下变量在 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());
}
}
}
}
但是当声明放置在 try{}
之前的 main()
中时,程序编译时没有错误,
有人能给我指出解决方案/答案/解决方法吗?
最佳答案
您需要在进入 try
block 之前声明变量,以便它们保留在方法的其余部分的范围内:
public static void main() throws FileNotFoundException {
File src = null;
File des = null;
try {
src = new File("src.txt");
des = new File("des.txt");
/*code*/
} finally {
/*closing code*/
if (src != null) {
System.out.print("After closing files:Size of src.txt:" + src.length() + " Bytes\t");
}
if (des != null) {
System.out.println("Size of des.txt:" + des.length() + " Bytes");
}
}
}
关于java - 从finally block 访问时try block 内的变量范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23249951/