Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to access 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 variable inside a try-catch block can't be accessed outside it but still I want to.

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){}
}   

it's a super serious problem for me in my project. I googled, and tried myself, but nothing solved.

I hope that now I will find some solution. 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.

like image 958
Ruman Khan Pathan Avatar asked Feb 22 '13 18:02

Ruman Khan Pathan


2 Answers

Just declare the boolean outside of the try/catch, and set the value in the try block

public boolean myMethod() {
    boolean success = false;
    try {
        doSomethingThatMightThrowAnException();
        success = true;
    }
    catch ( Exception e ) {
        e.printStackTrace();
    }
    return success;
}
like image 52
Lucas Avatar answered Sep 22 '22 12:09

Lucas


In your method, if an Exception is thrown, then there is no return statement. Place a return statement either in the exception handler, in a finally block, or after the exception handler.

like image 34
rgettman Avatar answered Sep 20 '22 12:09

rgettman