Reputation: 28294
I have a static initialization block. It sets up logging to a file. If something goes wrong, 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.
Upvotes: 5
Views: 2263
Reputation: 8842
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");
}
}
Upvotes: 1
Reputation: 117587
Is this what you're looking for?
label:
{
// blah blah
break label;
}
Upvotes: 2
Reputation: 10273
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.
Upvotes: 0
Reputation: 533502
Your static block can call a method
static { init(); }
private static void init() {
// do something
if(test) return;
// do something
}
Upvotes: 9
Reputation: 6875
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.
Upvotes: 4