Handle Exceptions thrown from Initializer Blocks in Java

This post is in continuation to exploring little-known features of Java. In the previous post, I covered some very surprising usage of class sun.misc.Unsafe. In this post, I am discussing a little-known feature of initializer blocks.

1. Initializer Blocks

An initialization block is a block of code between braces that is executed before the instance of the class is created and even before constructors are invoked. It is not at all necessary to include them in your classes.

Initializers can be used in two ways:

  • Instance initializer block: It is dependent on the object and the initialization block is executed for each object of the class that is created. It can initialize instance member variables of the class.
  • Static initializer block: It is defined using the keyword static and is executed once when the class is loaded and has a restriction that it can only initialize static data members of the class.

This is what we all know. Now coming to the part which many of us do not know before.

2. Initializer Blocks can throw Exceptions

Sometimes in the initializer block, you may need to write some code, which can throw checked exceptions. Checked exceptions are those exceptions that are checked at compile time and the compiler forces you to handle them in your code. Let’s take an example:

public class CheckedExceptionsFromConstrctor {

  Document doc = null;
  
  {
    doc = new SAXBuilder(false).build(new StringReader(new String("<users>")));
  }
}

The above code throws two checked exceptions: IOException and JDOMException. We can handle them using try-catch. e.g.

public class CheckedExceptionsFromConstrctor {

  Document doc = null;
  
  try {
    doc = new SAXBuilder(false).build(new StringReader(new String("<users>")));
  } catch (JDOMException | IOException e) {
    e.printStackTrace();
  }
}

If you do not wish to handle exceptions in the initializer and try to throw them, the compiler will not allow you to do this.

public class CheckedExceptionsFromConstrctor {

  Document doc = null;

  try {
    doc = new SAXBuilder(false).build(new StringReader(new String("<users>")));
  } catch (JDOMException | IOException e) {

    throw e;  //Not allowed
  }
}

3. Declare Exceptions from Instance Initializers into Constructor

Add the throws clause in constructors, and you will be able to throw the checked exceptions from initializers. e.g.

public class CheckedExceptionsFromConstrctor {

  Document doc = null;

  public CheckedExceptionsFromConstrctor() throws IOException, JDOMException {
    //constructor
  }

  {
    doc = new SAXBuilder(false).build(new StringReader(new String("<users>")));
  }
}

4. Static Initializers cannot throw Checked Exceptions

The above reasoning was for non-static or instance initializers. If you got static initializers in your class, then you MUST handle checked exceptions. You are not allowed to throw them in any possible way.

public class CheckedExceptionsFromConstrctor
{
  static Document doc = null;

  public CheckedExceptionsFromConstrctor() {
    //Some other code
  }

  static {
    try {
      doc = new SAXBuilder(false).build(new StringReader(new String("<users>")));
      
    } catch (JDOMException | IOException e) {
      e.printStackTrace();        //You must handle the exception here
    }
  }
}

That’s all around this topic. Hope you liked it. I will appreciate it if you share your thoughts in the comments section. And do not forget to subscribe through email, for new updates next to such little-known features.

Happy Learning !!

Comments

Subscribe
Notify of
guest
4 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.