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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With