Can static code blocks throw exceptions? [duplicate]

浪尽此生 提交于 2019-12-05 03:50:50

From JLS §11.2.3:

It is a compile-time error if a class variable initializer (§8.3.2) or static initializer (§8.7) of a named class or interface can throw a checked exception class.

For completeness, an unchecked exception is defined in JLS §11.1.1:

RuntimeException and all its subclasses are, collectively, the run-time exception classes.

The unchecked exception classes are the run-time exception classes and the error classes.

This is the only type of exception that can be thrown from a static initializer.

Static code blocks cannot throw Checked Exceptions, you can catch the checked exception, log it appropriately and throw a Runtime Exception. You would want to nest the checked exception as root cause.

However the exception you finally receive will be some form of ClassInitializationException and you can look into the nested exceptions to determine root cause.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!