Before the constructor is called, it must allocate memory for the object, so
the object is created, but because an exception is thrown from within the
constructor, no reference to the object exists, so the object will be
garbage collected at the earliest possible moment.
For example,
Rational r = new Rational( 0, 0 );
must first allocate memory for two ints, and then the constructor will throw
an exception, and therefore, new will never return a reference, and
therefore the memory allocated for the created rational cannot have a
reference to it and therefore it will be available for garbage collection.
Now, you can actually keep a reference to the object by passing it through
the exception... After some thought, I came up with the following two
classes:
public class Rational {
public int numer, denom; // yes, yes, I know, these are suppose to be
private, this is just for sample code...
public Rational( int n, int d ) {
if ( d == 0 )
throw new MyException( this );
numer = n;
denom = d;
}
public String toString() {
return numer + "/" + denom;
}
public static void main( String[] args ) {
try {
Rational r = new Rational( 0, 0 );
} catch( MyException e ) {
System.out.println( e.ratio ); // I'm printing it, and notice, it has a
zero in the denominator
Rational r = e.ratio;
r.numer = 3;
r.denom = 5;
System.out.println( r );
}
}
}
public class MyException extends RuntimeException {
public Rational ratio; // ditto, this should be private...
public MyException( Rational r ) {
ratio = r;
}
}
I pass a reference to the created object (i.e., 'this') through the
exception which was thrown.
Remember, the constructor is there to *initialize* the object, not to create
it, despite the misleading name.
Please don't hold it against anyone (TAs or other people) if they suggested
otherwise -- the above construction, I would strongly suggest, is subtle.
If you don't understand it, don't worry. If you don't understand it but
still want to, please talk to me.
Hopefully this example is clear at least to the original person who asked
the question. :-) In the answer to the original question, no, you don't
have to do anything, just throw the exception.
Cheers,
Douglas
Post by Adam BertrandIt depends on where you catch it, but I don't think that the object gets
created...
Adam
Post by prashantI was under the impression that when you throw an exception the process is
automatically stopped. You won't be able to create the object. (Then again i
could be wrong)
- Prashant
Post by Chris OlekasHi
I understand that we are supposed to throw a runtime exception for when
a rational with the denominator of 0 is created. But won't that rational
object still be created?
Are we supposed to stop the creation of the object? Or just have it stay
around?
Chris