How to throw an exception from a static block in Java?

JavaObject Oriented ProgrammingProgramming

A static block is a set of statements, which will be executed by the JVM before the execution of the main() method. At the time of class loading if we want to perform any activity we have to define that activity inside a static block because this block executes at the time of class loading.

Throw an exception from a Static Block

  • A static block can throw only a RunTimeException, or there should be a try and catch block to catch a checked exception.
  • A static block occurs when a class is loaded by a class loader. The code can either come in the form of a static block or as a call to a static method for initializing a static data member.
  • In both cases, checked exceptions are not allowed by the compiler. When an unchecked exception occurs, it is wrapped by the ExceptionInInitializerError, which is then thrown in the context of the thread that triggered the class loading.
  • Trying to throw a checked exception from a static block is also not possible. We can have a try and catch block in a static block where a checked exception may be thrown from the try block but we have to resolve it within the catch block. We can’t propagate it further using a throw keyword.

Example

Live Demo

public class StaticBlockException {
   static int i, j;
   static {
      System.out.println("In the static block");
      try {
         i = 0;
         j = 10/i;
      } catch(Exception e){
         System.out.println("Exception while initializing" + e.getMessage());
         throw new RuntimeException(e.getMessage());
      }
   }
   public static void main(String args[]) {
      StaticBlockException sbe = new StaticBlockException();
      System.out.println("In the main() method");
      System.out.println("Value of i is : "+i);
      System.out.println("Value of j is : "+ j);
   }
}

Output

In the static block
Exception while initializing/ by zero
Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: java.lang.RuntimeException: / by zero
        at StaticBlockException.(StaticBlockException.java:10)
raja
Published on 17-Jun-2019 15:11:18
Advertisements