What happens if an exception occurs in the initialization block?
sobes.tech AI
Answer from AI
If an exception occurs in a static initializer block, it will be wrapped in an ExceptionInInitializerError and thrown upon the first access to a static member of the class or when the class is loaded. The class will remain in an uninitialized state, and any subsequent access to it will result in the same error being thrown again.
If an exception occurs in an instance initializer block, it will be thrown during the creation of a new class instance (in the constructor) and will prevent the object from being created.
class Example {
static {
// Static initializer block
if (true) {
throw new RuntimeException("Error in static initializer");
}
}
{
// Instance initializer block
if (true) {
throw new RuntimeException("Error in instance initializer");
}
}
public Example() {
System.out.println("Constructor called");
}
public static void staticMethod() {
System.out.println("Static method");
}
}
public class Main {
public static void main(String[] args) {
try {
Example.staticMethod(); // Attempt to access static member
} catch (Throwable e) {
// ExceptionInInitializerError will be thrown
System.out.println("Caught error: " + e);
}
try {
new Example(); // Attempt to create an instance
} catch (Throwable e) {
// RuntimeException will be thrown (wrapped in ExceptionInInitializerError if static initializer completed before instance initializer)
System.out.println("Caught error: " + e);
}
}
}
In the case of a static initializer, the exception indicates a fundamental problem with the class, making it unusable. In the case of an instance initializer, the problem pertains to a specific instance, preventing its creation.