variable scope inside the try block when accessing from the finally block?

前端 未结 1 873
一整个雨季
一整个雨季 2021-01-25 07:34

I noticed that when the following variables when in try { }, I couldn\'t use methods on them from finally for example:

import java.io.*;
public class Main 
{
             


        
相关标签:
1条回答
  • 2021-01-25 08:35

    You need to declare your variables before you enter your try block, so that they remain in scope for the rest of your method:

    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");
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题