Saturday, 15 September 2018

Can I throw an exception from static block?

Yes, you can throw a runtime exception from static block.

Connection.java
package com.sample.app;

public class Connection {
 static {
  int a = 10;

  if (a == 10) {
   throw new RuntimeException("Error Occured while loading the class");
  }

 }
}

Application.java
package com.sample.app;

public class Application {

 public static void main(String args[]) {
  new Connection();
 }
}


When you ran Application.java, you can see below messages in console.
Exception in thread "main" java.lang.ExceptionInInitializerError
         at com.sample.app.Application.main(Application.java:6)
Caused by: java.lang.RuntimeException: Error Occured while loading the class
         at com.sample.app.Connection.<clinit>(Connection.java:8)
         ... 1 more

Can’t I throw checked exception?
You can’t throw the checked exception directly. But you can throw the checked exception by wrapping it inside RuntimeException.

Connection.java
package com.sample.app;

public class Connection {
 static {
  int a = 10;

  if (a == 10) {
   try {
    throw new Exception("Error Occured while loading the class");
   } catch (Exception e) {
    throw new RuntimeException(e);
   }
  }

 }
}

When you ran Application.java, you can see below messages in the console.

Exception in thread "main" java.lang.ExceptionInInitializerError
         at com.sample.app.Application.main(Application.java:6)
Caused by: java.lang.RuntimeException: java.lang.Exception: Error Occured while loading the class
         at com.sample.app.Connection.<clinit>(Connection.java:11)
         ... 1 more
Caused by: java.lang.Exception: Error Occured while loading the class
         at com.sample.app.Connection.<clinit>(Connection.java:9)

         ... 1 more

You may like

No comments:

Post a Comment