Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Netbeans Java complaining about final variable not being initialised

Tags:

java

netbeans

Consider this code:

final MyClass myObject;
try {
    myObject = new MyClass(...)
} catch (MyClassException){
    // terminate
    System.exit(1);
}

myObject.doSomething();

The problem is that the Netbeans editor / parser thinks that .doSomething() could be called on an unitialised object which, of course, is not the case.

Is there an normal / standard pattern for circumventing this? I could call into a function but would rather not do that. I'd also rather not enclose the whole block in the try catch block since nothing else throws MyClassException

I'm not (yet ;-) ) an expert on Java grammar and patterns so am hope I'm missing something obvious.

like image 917
Bathsheba Avatar asked May 15 '26 19:05

Bathsheba


1 Answers

You initialize your object in try block, which may throw exception, leaving object uninitialized.

In your catch block, you stop your program, but System.exit(1) does not stop method execution, instead, it terminates currently running JVM - and for compiler it's just another method you call if an exception is thrown.

return actually stops method execution - so no code beyond return; is reached. You can modify your catch block as following:

catch (MyClassException){
    // terminate
    System.exit(1);
    return;
}

Compiler won't complain about myObject not being initialized this way.

EDIT

NB: if you put myObject.doSomething(); in finally block compiler WILL complain, since finally is executed even after return.

finally {
    // compiler error
    myObject.doSomething();
}
like image 146
Vladimir Avatar answered May 17 '26 08:05

Vladimir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!