Java Is it possible to initialize final variables in a static initialization block?

Based on my understanding of the Java language, static variables can be initialized in a static initialization block .

However, when I try to put this into practice ( static variables that are final too), I get the error shown in the screenshot below:

/img/1b2862e9d0ae2e745a1beed2fa31b58a.jpg

+41
java static final
Feb 26 2018-10-12T00
source share
4 answers

Yes, of course: static final variables can be initialized in a static block, but .... you have implicit GOTOs in this example ( try/catch is essentially "GOTO catch if something is wrong").

If an exception is thrown, your final variables will not be initialized.

Note that using static constructions goes against object-oriented dogma. This can complicate your testing and make debugging difficult.

+33
Feb 26 '10 at 6:50
source share

You can do this, but you need to exit the static block by throwing an exception - you can rebuild the exception that was caught or a new one. Usually this exception should be a RuntimeException . You really shouldn't catch a general Exception , but a more specific exception (s) that can be thrown from your try block. Finally, if the static initializer throws an exception, it will render the class unusable during this particular run, because the JVM will try to initialize your class only once. Subsequent attempts to use this class will result in another exception, such as NoClassDefFoundError .

So, in order to work, your initializer must read something like this:

 static { try { ... } catch (Exception e) { e.PrintStackTrace(); throw new InitializationFailedException("Could not init class.", e); } } 

Assuming InitializationFailedException is a custom RuntimeException , but you can use an existing one.

+17
Feb 26 '10 at 7:02
source share
 public class MyClass { private static final SomeClass myVar; static { Object obj = null; // You could use SomeClass, but I like Object so you can reuse it try { obj = new SomeClass(...); } catch(WhateverException err) { // Possibly nested try-catches here if the first exception is recoverable... // Print an error, log the error, do something with the error throw new ExceptionInInitializerError(err); } finally { myVar = (SomeClass) obj; } } } 

Assuming the upstream is able to catch an ExceptionInInitializationError or a general exception, then the program should never try to use myVar . If, however, they are caught and the program does not end, then you need to code to watch and handle myVar , which is null (or to be happy with NullPointerExceptions coming out everywhere).

I'm not sure there is a good way to handle this.

+8
Nov 28 '11 at 17:01
source share

Can you put an ad in a finally block?

 try { //load file } catch(IOException e) { // horay } finally { HOST=config.get...... } 
0
Mar 20 '11 at 16:35
source share



All Articles