Member-only story
What Happens If an Exception Is Thrown in a static
Block | Tricky Java Interview Questions — Part 19
Hello Developers,
Welcome to Part 19 of the Tricky Java Interview Questions series.
Here’s today’s classic question:
What happens if an exception is thrown in a
static
block in Java?
At first, it seems like any other exception-handling question — but static blocks operate during class loading, which makes the answer different and important.
Let’s explore.
Quick Recap: What Is a Static Block?
A static
block is a class-level initializer in Java. It runs once, when the class is loaded by the JVM, before any constructor or method is invoked.
Example:
public class Demo {
static {
System.out.println("Static block executed");
}
}
This block runs only once, the first time Demo
is loaded into memory.
Now What If It Throws an Exception?
Let’s test it:
public class Problematic {
static {
System.out.println("Static block starts");
int x = 1 / 0; // ArithmeticException
System.out.println("Static block ends");
}
public static void sayHello() {
System.out.println("Hello");
}
}