Issue
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.
Solution
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();
}
Answered By - Vladimir
Answer Checked By - Senaida (JavaFixing Volunteer)