A static block can throw an exception during class initialization, but checked exceptions cannot be propagated directly from a static block. Any checked exception must be handled within the block. If an unchecked exception occurs and is not handled, class initialization fails and the JVM throws an ExceptionInInitializerError.
Key Points: • Static blocks execute when the class is loaded into memory. • Checked exceptions must be handled inside the static block. • Unchecked exceptions (RuntimeException) can be thrown from a static block. • An unhandled exception in a static block prevents the class from loading properly. • The JVM wraps unhandled exceptions in ExceptionInInitializerError.
Example: Suppose a class performs initialization in a static block. If an unexpected error occurs and is not handled, the class initialization will fail.
Code Example:
class Demo {
static {
int result = 10 / 0;
System.out.println(result);
}
public static void main(String[] args) {
System.out.println("Main Method");
}
}Output:
Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: java.lang.ArithmeticException: / by zero
Handling Checked Exceptions:
class Demo {
static {
try {
Class.forName("com.mysql.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}In this example, the checked exception is handled inside the static block.
Why Can't Checked Exceptions Be Declared?
A static block is not a method, constructor, or initializer that supports a throws clause. Therefore, checked exceptions must be caught and handled within the block itself.
Common Use Cases of Static Blocks:
• Initializing static variables • Loading configuration data • Registering drivers • Performing one-time class initialization
Important Note:
If a static block fails due to an unhandled exception:
• The class is not initialized. • The JVM throws ExceptionInInitializerError. • Further attempts to use the class may result in NoClassDefFoundError.
Interview Tip: A concise interview answer is:
"A static block can throw an exception, but checked exceptions must be handled inside the block because static blocks cannot declare a throws clause. If an unchecked exception is not handled, class initialization fails and the JVM throws an ExceptionInInitializerError."