Java: When is a static initialization block useful?

前端 未结 13 1644
时光说笑
时光说笑 2020-11-30 16:49

What\'s the difference between initialization within a static block:

public class staticTest {

    sta         


        
13条回答
  •  旧巷少年郎
    2020-11-30 17:00

    Exception handling during initialization is another reason. For example:

    static URL url;
    static {
        try {
            url = new URL("https://blahblah.com");
        }
        catch (MalformedURLException mue) {
            //log exception or handle otherwise
        }
    }
    

    This is useful for constructors that annoyingly throw checked exceptions, like above, or else more complex initialization logic that might be exception-prone.

提交回复
热议问题