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.
6 Answers
Is this what you're looking for?
label:
{
// blah blah
break label;
}
6 Comments
user489041
Can you break to a label that is below the break statement?
Peter Lawrey
The label has to be at the start of a block, the place to break to is at the end of the block.
dhblah
@user48 you don't break to label, you break the label
Laurent Pireyn
A
break with label is only useful if it is nested more than one level deeper than the label. Otherwise, it's just bad coding style since it can be avoided in a more readable way.Clockwork-Muse
You cannot use labels to branch to an arbitrary place in the code (so no, you can't go to a label that is below the current code). That is a valid use of the label - when it hits the label, it's going to go to the label, then skip over the section that was labelled (so,
// blah blah won't get executed a second time). |
- 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"); } }
1 Comment
Sean Patrick Floyd
please don't use HTML code tags. just indent your code (4 spaces or 8 inside a list) and code will be displayed nicely.
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.
static finalvariables should be initialized, regardless...