How to handle a static final field initializer that throws checked exception

后端 未结 4 1112
迷失自我
迷失自我 2020-12-02 17:01

I am facing a use case where I would like to declare a static finalfield with an initializer statement that is declared to throw a checked exception. Typically,

4条回答
  •  余生分开走
    2020-12-02 17:30

    If you don't like static blocks (some people don't) then an alternative is to use a static method. IIRC, Josh Bloch recommended this (apparently not in Effective Java on quick inspection).

    public static final ObjectName OBJECT_NAME = createObjectName("foo:type=bar");
    
    private static ObjectName createObjectName(final String name) {
        try {
            return new ObjectName(name);
        } catch (final SomeException exc) {
            throw new Error(exc);
        }  
    }
    

    Or:

    public static final ObjectName OBJECT_NAME = createObjectName();
    
    private static ObjectName createObjectName() {
        try {
            return new ObjectName("foo:type=bar");
        } catch (final SomeException exc) {
            throw new Error(exc);
        }  
    }
    

    (Edited: Corrected second example to return from method instead of assign the static.)

提交回复
热议问题