Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

inside try block a FileIStream variable might not have been initialized error

I am trying to execute this code and I am also providing the valid argument but still I am getting error at line no. 34 and 35 that local variable fin and fout might not have been initialized. How to solve thisenter code here

 package maxbj.myTest.p1;
import java.io.*;
public class CopyFile {
public static void main(String[] args)throws IOException {

    int i;
    FileInputStream fin;
    FileOutputStream fout;

    try{
        //trying to open input file
        try{
            fin=new FileInputStream(args[0]);
        }catch(FileNotFoundException e){
            System.out.println("Input file not found");
            return;
        }

        //trying to open output file
        try{
            fout=new FileOutputStream(args[1]);
            return;
        }catch(FileNotFoundException e){
            System.out.println("Output file cannot be opened or created");
            return;
        }       
    }catch(ArrayIndexOutOfBoundsException e){
        System.out.println("Array index out of bound exception");
    }

    //code to copy file
    try{
        do{
            i=fin.read();
            if(i!=-1) fout.write(i);
        }while(i!=-1);
    }catch(IOException e){
        System.out.println("File Error");
    }
    fin.close();
    fout.close();
}
}

PS- This code is from the book "JAVA COMPLETE REFRENCE"

like image 602
Bijay Singh Avatar asked Oct 16 '25 02:10

Bijay Singh


1 Answers

The compiler is right (and the book is wrong, they should have tried compiling their code before publishing): there is a path through the code when fin remains uninitialized by the time the code reaches the fin.read() line.

Specifically, if ArrayIndexOutOfBoundsException gets thrown in the first outer try/catch block, the fin variable will not be assigned. Adding return to the outer catch block should fix this problem:

try {
    ...
} catch(ArrayIndexOutOfBoundsException e){
    System.out.println("Array index out of bound exception");
    return; // <<== Here
}

With the return statement in place, control will never reach the fin.read() unless fin has been initialized, fixing the compile-time error.

like image 80
Sergey Kalinichenko Avatar answered Oct 18 '25 15:10

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!