Breaking from Static Initialization Block in Java
I have a static initialization block. It sets up logging to a file. If something goes w开发者_开发知识库rong, I simply want to break out of the static block. Is this possible? I know I could use an if/else approach, but using a simple break would make the code much more readable.
Your static block can call a method
static { init(); }
private static void init() {
// do something
if(test) return;
// do something
}
You probably want to catch all exceptions:
static {
try {
// Initialization
}
catch (Exception exception) {
// Not much can be done here
}
}
But beware: loading the class won't fail, but some or all static fields could be in an inconsistent state.
Is this what you're looking for?
label:
{
// blah blah
break label;
}
- if it is an exception, use try{throw new Exception();}catch
if it is normal processing, use if-then-else or switch
eventually you could use labels, but IMHO it is a very bad style://boolean condition; static { label: { System.out.println("1"); if(condition) break label; System.out.println("2"); } }
How about try/catch ?
try{}catch(){}
In my opinion, a static block is not different from any other block in terms of flow control strategies to use. You can use BREAK wherever if you find it more readable (in your static block also) but the general assumption is that it makes the code less readable in fact, and that a IF ELSE approach is better.
精彩评论