Java 从finally块访问时try块内的变量范围?
我注意到,在try{}中使用以下变量时,我无法使用finally中的方法,例如:Java 从finally块访问时try块内的变量范围?,java,try-catch,block,scope,finally,Java,Try Catch,Block,Scope,Finally,我注意到,在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.
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{}
程序编译时没有错误,
有人能告诉我解决方案/答案/解决方法吗?在输入
try
块之前,您需要声明变量,以便它们在方法的其余部分保持在范围内:
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");
}
}
}
当声明放在main()之前,请尝试{}
这就是解决方案。在更大范围内声明变量。没有解决方法。这是java中的预期行为。变量作用域是严格的。如果在块内声明任何变量,如{
或}
,则无法在作用域外访问它。