English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Why can't variables defined in a try block be used in a catch block or be final in Java?

In Java, a class will have three types of variables, namely static (class), instance, and local variables.

  • Instance variables-These variables belong to the instance (object) of the class. These are declared within the class but outside the method. These are initialized when the class is instantiated. They can be accessed from any method, constructor, or block of the specific class.

  • Class/Static variables-Class/Static variables belong to the class, just like instance variables, they are declared outside any method within the class, but declared using the static keyword.

    They can be accessed at compile time, and you can access them before instantiation/When accessing without instantiating the class, there is only one copy of the static field available throughout the entire class, that is, the value of the static field is the same in all objects. You can define a static field using the static keyword.

  • Local variables-These variables belong to the method/Block/Constructor and declare within it/Definition. The scope of these variables is within the method (or block or constructor), and they will be destroyed after execution.

Variables in the try block

Therefore, if a variable is declared in a try block (and this applies to any block), the variable will be local to that specific block, the lifetime of the variable will expire after the execution of the block. Therefore, you cannot access any variable declared in a block outside of it.

Example

In the following example, we declare a variable named result and try to access it in the finally block, which will cause a compile-time error at compile time.

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 occurred");
      } finally {
         System.out.println("This is finally block");
         System.out.println("Result ",+arr[a]+"/"+arr[b]+: "+result);
      }
   }
}

Output Result

ExceptionExample.java:21: error: cannot find symbol
      System.out.println("Result ",+arr[a]+"/"+arr[b]+: "+result);
                                                            ^
   symbol: variable result
   location: class ExceptionExample
1 error