The "problem" you link to seems to be describing this situation:
SomeObject so;
try {
// Do some work here ...
so = new SomeObject();
so.DoUsefulThings();
} finally {
so.CleanUp(); // Compiler error here
}
The commenter's complaint is that the compiler balks at the line in the finally
section, claiming that so
might be uninitialized. The comment then mentions another way of writing the code, probably something like this:
// Do some work here ...
SomeObject so = new SomeObject();
try {
so.DoUsefulThings();
} finally {
so.CleanUp();
}
The commenter is unhappy with that solution because the compiler then says that the code "must be within a try." I guess that means some of the code may raise an exception that isn't handled anymore. I'm not sure. Neither version of my code handles any exceptions, so anything exception-related in the first version should work the same in the second.
Anyway, this second version of code is the correct way to write it. In the first version, the compiler's error message was correct. The so
variable might be uninitialized. In particular, if the SomeObject
constructor fails, so
will not be initialized, and so it will be an error to attempt to call so.CleanUp
. Always enter the try
section after you have acquired the resource that the finally
section finalizes.
The try
-finally
block after the so
initialization is there only to protect the SomeObject
instance, to make sure it gets cleaned up no matter what else happens. If there are other things that need to run, but they aren't related to whether the SomeObject
instance was property allocated, then they should go in another try
-finally
block, probably one that wraps the one I've shown.
Requiring variables to be assigned manually before use does not lead to real problems. It only leads to minor hassles, but your code will be better for it. You'll have variables with more limited scope, and try
-finally
blocks that don't try to protect too much.
If local variables had default values, then so
in the first example would have been null
. That wouldn't really have solved anything. Instead of getting a compile-time error in the finally
block, you'd have a NullPointerException
lurking there that might hide whatever other exception could occur in the "Do some work here" section of the code. (Or do exceptions in finally
sections automatically chain to the previous exception? I don't remember. Even so, you'd have an extra exception in the way of the real one.)