Static modifier, initialization blocks and exceptions in it in Java
Which Java constructs does the static modifier apply to
- fields;
- methods;
- nested classes;
- members of the import section.
What are static initialization blocks used for in Java
Static initialization blocks are used to execute code that must be executed once when the class is initialized by the class loader, at the moment before the objects of this class are created using the constructor. Such a block (as opposed to non-static ones belonging to a specific class object) belongs only to the class itself (the class metaclass object).
What happens if an exception is thrown in the initialization block
For non-static initialization blocks, if throwing an exception is explicitly required, the declarations of these exceptions must be listed in the throws of all class constructors. Otherwise there will be a compilation error. Explicitly throwing an exception for a static block results in a compilation error.
In other cases, interaction with exceptions will be the same as in any other place. The class will not be initialized if an error occurs in a static block and the class object will not be created if an error occurs in a non-static block.
What kind of exception is thrown when an error occurs in the class initialization block
If the thrown exception is inherited from RuntimeException:
- java.lang.ExceptionInInitializerError will be thrown for static initialization blocks;
- for non-static ones, the source exception will be thrown.
If the thrown exception is inherited from Error, then in both cases java.lang.Error will be thrown. Exception: java.lang.ThreadDeath - death of a thread. In this case, no exception will be thrown.
Read also:
- Can an object access a private member of a class in Java
- How is an abstract class different from an interface in Java
- What is the order of calling constructors and initialization blocks, given the class hierarchy
Comments
Post a Comment