Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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, it'd look like this:

public static final ObjectName OBJECT_NAME = new ObjectName("foo:type=bar"); 

The issue I have here is that the ObjectName constructor may throw various checked exceptions, which I don't care about (because I'd know my name is valid, and it's allright if it miserably crashes in case it's not). The java compiler won't let me just ignore this (as it's a checked exception), and I would prefer not to resort to:

public static final ObjectName OBJECT_NAME; static {     try {         OBJECT_NAME = new ObjectName("foo:type=bar");     } catch (final Exception ex) {         throw new RuntimeException("Failed to create ObjectName instance in static block.", ex);     } } 

Because static blocks are really, really difficult to read. Does anyone have a suggestion on how to handle this case in a nice, clean way?

like image 227
Romain Avatar asked Dec 08 '09 12:12

Romain


People also ask

Can we throw checked exceptions from the static block?

A static block can throw only a RunTimeException, or there should be a try and catch block to catch a checked exception.

Can we throw exception from static method in Java?

Its perfectly legal in java to throw exceptions from static methods.


2 Answers

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.)

like image 86
Tom Hawtin - tackline Avatar answered Oct 01 '22 10:10

Tom Hawtin - tackline


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.

like image 40
BalusC Avatar answered Oct 01 '22 08:10

BalusC