Search code examples
javareturntry-catchreturn-value

How to access a variable outside a try catch block


I'm trying to return a boolean value from my function having try-catch block,

But the problem is I cant return any value.

I know that a variable inside a try-catch block can't be accessed outside it, but still I want to access it somehow.

public boolean checkStatus(){
        try{
        
        
        InputStream fstream = MyRegDb.class.getClassLoader().getResourceAsStream("textfile.txt");
        // Use DataInputStream to read binary NOT text.
        BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
        String strLine;
                                                
        //Read File Line By Line
        strLine = br.readLine();
        // Print the content on the console
        System.out.println (strLine);
        
        ind.close();
        if(strLine.equals("1")){
            
            return false;   
        }else{
            return true;    
        }
        
    }catch(Exception e){}
}   

I know that it has error saying return statement missing but I want program exactly working like this.

Now the reason I'm strict to this

In my jar file I have to access text files for finding values 1 or 0 if "1" then activate else deactivate.

that is why I am using Boolean.


Solution

  • The error is that you are not returning anything in the case where an exception is thrown.

    try the following:

    public boolean checkStatus(){
       boolean result = true;  // default value.
       try{
    
            InputStream fstream = MyRegDb.class.getClassLoader().getResourceAsStream("textfile.txt");
            // Use DataInputStream to read binary NOT text.
            BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
            String strLine;
    
            //Read File Line By Line
            strLine = br.readLine();
            // Print the content on the console
            System.out.println (strLine);
    
            ind.close();
            if(strLine.equals("1")){
    
                result = false;   
            }else{
                result = true;    
            }
    
        }catch(Exception e){}
        return result;
    }