user11481705
user11481705

Reputation:

How can I access a variable from outside the try catch block?

I'm getting a "len cannot be resolved to a variable" error here

        try {
            byte len = (byte) passLength();
        }
        catch(Exception InputMismatchException) {
            System.out.println("Error, please input a proper number");
        }
        finally {
            String result = passGen(len, chars);
            System.out.println(result);
        }

Upvotes: 0

Views: 4317

Answers (4)

Akil Kumar
Akil Kumar

Reputation: 58

Scope of a variable: As a general rule, variables that are defined within a block are not accessible outside that block.

Lifetime of a variable: Once a variable loses it scope, Garbage collector will takes care of destroying the variable/object. The lifetime of a variable refers to how long the variable exists before it is destroyed.

try {
     byte len = (byte) passLength();
}

In your above example, the variable len is declared inside the try block, its scope is only within the try block and can't be accessed outside the try block.

You should declare the len variable even before the try block, so that it can be accessed in the finally block.

byte len = Byte.MIN_VALUE;  //This value is for dummy assignment
try {
     len = (byte) passLength();
} catch(Exception inputMismatchException) { // Avoid using variable name starts with Capitals
     System.out.println("Error, please input a proper number");
} finally {
     String result = passGen(len, chars);
     System.out.println(result);
}

Hope, this will be helpful :)

Upvotes: 1

Lavneesh Chandna
Lavneesh Chandna

Reputation: 141

Declare the variable outside the scope of try block. Finally block cannot access the scope of try block.

        byte len = 0;
        try {
            len = (byte) passLength();
        }
        catch(Exception InputMismatchException) {
            System.out.println("Error, please input a proper number");
        }
        finally {
            String result = passGen(len, chars);
            System.out.println(result);
        }

Upvotes: 0

Gaurav Dhiman
Gaurav Dhiman

Reputation: 1023

Because you have declared len variable inside try block and its scope is in try block itself and is not accessible in finally block. Try declaring len outside the try block. It would work.

Upvotes: 0

Varun Mukundhan
Varun Mukundhan

Reputation: 278

If the try block encounters an exception, the len variable would be undefined.

If you're sure an exception wouldn't occur, you may initialize a temporary byte variable before the try-catch block.

byte temp;
try {
            byte len = (byte) passLength();
            temp = len;

 } catch(Exception InputMismatchException) {
            System.out.println("Error, please input a proper number");
 }
 finally {
     String result = passGen(temp, chars);
     System.out.println(result);
 }

Upvotes: 0

Related Questions