Re: exception inside constructors and finalize
- From: Patricia Shanahan <patricia_shanahan@xxxxxxxxxxxxx>
- Date: Thu, 28 Apr 2005 12:54:15 GMT
Ross Bamford wrote:
....
An exception handled within a constructor is a regular exception, but one thrown by a constructor *should* result in the object not being allocated, or deallocated immediately. It *always* leaves the object in an undefined state (Null in my experience but don't rely on it)
For example the following code:
public class Test
{
public String tester;
public Test() throws Exception
{
tester = "Tester object";
throw(new Exception()); }
public static void main(String args[])
{
Test t = null;
try {
t = new Test();
} catch (Exception e) { /* ignore */ }
String s = (t == null) ? "Null object" : t.tester;
System.out.println(s);
}
}
produces the output "Null object", unless we remove the throws clause from the constructor (when it's "Tester object" obviously).
I agree generally with your comments, but I don't think you got this one quite right.
t is null because you initialized it to null, and nothing changed it between initialization and the null test. You can count on an assignment not happening if evaluation of its right hand side completes abruptly.
Memory for the object is allocated, and any initialization that happens before the exception gets done. Whether the object is immediately eligible for garbage collection depends, as always, on its reachability.
Here's a variation of your program that demonstrates this.
public class ConstructorTest
{
static ConstructorTest lastConstructed = null;
public String tester; public ConstructorTest() throws Exception
{
lastConstructed = this;
tester = "ConstructorTest object";
throw(new Exception());
} public String toString()
{
return tester;
} public static void main(String args[])
{
Object t = "Not a ConstructorTest object";
try {
t = new ConstructorTest();
} catch (Exception e) { /* ignore */ } String s = (t == null) ? "Null object" : t.toString();
System.out.println(s);
if(lastConstructed != null)
{
System.out.println(lastConstructed);
}
}
}It prints:
Not a ConstructorTest object ConstructorTest object
Patricia
.
- Follow-Ups:
- Re: exception inside constructors and finalize
- From: Ross Bamford
- Re: exception inside constructors and finalize
- References:
- exception inside constructors and finalize
- From: sarath
- Re: exception inside constructors and finalize
- From: Tor Iver Wilhelmsen
- Re: exception inside constructors and finalize
- From: Ross Bamford
- exception inside constructors and finalize
- Prev by Date: Re: exception inside constructors and finalize
- Next by Date: Class within a class
- Previous by thread: Re: exception inside constructors and finalize
- Next by thread: Re: exception inside constructors and finalize
- Index(es):