Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Breaking from Static Initialization Block in Java

Tags:

java

static

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.

like image 543
user489041 Avatar asked Jul 12 '11 15:07

user489041


3 Answers

Your static block can call a method

static { init(); }

private static void init() {
     // do something
     if(test) return;
     // do something
}
like image 99
Peter Lawrey Avatar answered Oct 12 '22 14:10

Peter Lawrey


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.

like image 29
Laurent Pireyn Avatar answered Oct 12 '22 16:10

Laurent Pireyn


Is this what you're looking for?

label:
{
  // blah blah
  break label;
}
like image 2
Eng.Fouad Avatar answered Oct 12 '22 14:10

Eng.Fouad