Why variables defined in try cannot be used in catch or finally in java?

Java 8Object Oriented ProgrammingProgramming

A class in Java will have three kinds of variables namely, static (class), instance and, local.

  • Instance variables − These variables belong to the instances (objects) of a class. These are declared within a class but outside methods. These are initialized when the class is instantiated. They can be accessed from any method, constructor or blocks of that particular class.

  • Class/static variables − class/static variables belong to a class, just like instance variables they are declared within a class, outside any method, but, with the static keyword.

    They are available to access at the compile time, you can access them before/without instantiating the class, there is only one copy of the static field available throughout the class i.e. the value of the static field will be same in all objects. You can define a static field using the static keyword.

  • Local variables − These variables belong to and declared/defined within the methods/blocks/constructors. The scope of these variables lies within the method (or, block or, constructor) and will be destroyed after he execution of it.

Variables in try block

So, if you declare a variable in try block, (for that matter in any block) it will be local to that particular block, the life time of the variable expires after the execution of the block. Therefore, you cannot access any variable declared in a block, outside it.

Example

In the following example we have declared a variable named result and we are trying to access it in the finally block, on compiling, it generates a compile time error.

import java.util.Arrays;
import java.util.Scanner;
public class ExceptionExample {
   public static void main(String [] args) {
      Scanner sc = new Scanner(System.in);
      int[] arr = {10, 20, 30, 2, 0, 8};
      System.out.println("Array: "+Arrays.toString(arr));
      System.out.println("Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)");
      int a = sc.nextInt();
      int b = sc.nextInt();
      try {
         int result = (arr[a])/(arr[b]);
      }catch(Exception e) {
         System.out.println("exception occured");
      } finally {
         System.out.println("This is finally block");
         System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result);
      }
   }
}

Output

ExceptionExample.java:21: error: cannot find symbol
      System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result);
                                                            ^
   symbol: variable result
   location: class ExceptionExample
1 error
raja
Published on 06-Aug-2019 07:35:26
Advertisements