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

后端 未结 4 1087
迷失自我
迷失自我 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:20

    static blocks aren't difficult to read. So I'd recommend that solution. However, you can wrap your object in another object, for example ObjectNameWrapper which shares an interface with your ObjectName, and whose constructor calls your ObjectName constructor, hiding all checked exceptions that occur. But again, I'd go for the static option.

    0 讨论(0)
  • 2020-12-02 17:28

    You can use a method annotated with Lombok's @SneakyThrows

    public static final ObjectName OBJECT_NAME = createObjectName();
    
    @SneakyThrows(SomeException.class)
    private static ObjectName createObjectName() {
        return new ObjectName("foo:type=bar");
    }
    

    This annotation makes a checked exception behaves like an unchecked one.

    0 讨论(0)
  • 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.)

    0 讨论(0)
  • 2020-12-02 17:30

    Your code is perfectly valid. I don't find it difficult to read. Other ways would only make it more worse. They're only difficult to read for starters, because most of them are not familiar with that. Just follow the standard conventions with regard to ordering of the elements in the code. E.g. do not put static initializers halfway or at the whole bottom of the code and also do not have multiple of them spreading over the class. Just put one at top, after static declarations.

    0 讨论(0)
提交回复
热议问题