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


i facing use case declare static finalfield initializer statement declared throw checked exception. typically, it'd this:

public static final objectname object_name = new objectname("foo:type=bar");

the issue have here objectname constructor may throw various checked exceptions, don't care (because i'd know name valid, , it's allright if miserably crashes in case it's not). java compiler won't let me ignore (as it's checked exception), , prefer not 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 create objectname instance in static block.",ex);     }   } 

because static blocks really, difficult read. have suggestion on how handle case in nice, clean way?

if don't static blocks (some people don't) alternative use static method. iirc, josh bloch recommended (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 return method instead of assign static.)


Comments

Popular posts from this blog

java - Intellij Synchronizing output directories .. -

git - Initial Commit: "fatal: could not create leading directories of ..." -