JAVA-TRICK-2: Can You Catch an Exception Thrown in a Static Block?

JAVA-TRICK-2: Can You Catch an Exception Thrown in a Static Block?

Question:

What happens if an exception is thrown in a static block?

Explanation:

Exceptions thrown in a static block can only be caught within a static initializer block using a try-catch. Otherwise, the program will fail to load the class.

Example:

class Test {
    static {
        try {
            int result = 10 / 0;
        } catch (ArithmeticException e) {
            System.out.println("Exception caught: " + e);
        }
    }
public static void main(String[] args) {
        System.out.println("Main method executed");
    }
}        

Output:

Exception caught: java.lang.ArithmeticException: / by zero
Main method executed        

要查看或添加评论,请登录

Chamseddine Toujani的更多文章

社区洞察

其他会员也浏览了