Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / First Aid / April 2005

Tip: Looking for answers? Try searching our database.

exception inside constructors and finalize

Thread view: 
sarath - 28 Apr 2005 04:37 GMT
i have some doubts.... please clear them.

1.how can we handle exception inside constructors and finalize method?
2.what will happen when an exception occur inside constructors and
finalize()?
will it be properly garbage collected ?
3.can we call finalize method explicitly ? and what will happen then ?

thanks in advance

sarath
Tor Iver Wilhelmsen - 28 Apr 2005 07:39 GMT
> 1.how can we handle exception inside constructors and finalize method?

try/catch or (for constructors) throws clause - as usual.

> 2.what will happen when an exception occur inside constructors and
> finalize()?

Same as happens when it occurs anywhere else: You need to pass it on
or catch it. Since finalize() is inherited from Object, you cannot add
any exception throws in it.

> will it be properly garbage collected ?

What do you mean? An exception object- like any other, will be a
candidate for collection as soon as it's no longer used.

> 3.can we call finalize method explicitly ? and what will happen then ?

It's a method, so you can call it yourself. What will happen is that
the code will be executed. Since you are calling it outside it's
normal lifecycle use, you might screw up your program doing so, if it
releases any resources or things like that.
Ross Bamford - 28 Apr 2005 10:29 GMT
> > 1.how can we handle exception inside constructors and finalize method?
>
[quoted text clipped - 18 lines]
> normal lifecycle use, you might screw up your program doing so, if it
> releases any resources or things like that.

I think OP meant 'happen to the Object'. Just to clear up.

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).

As for Finalize, it's not a 'destructor' - just a method Java calls when
it [feels like it and might be] about to destroy that object. You could
throw a RuntimeException from it, but the object would still be
deallocated.

Finalize is an empty method, provided by the API for you to perform
special actions at (or around) GC time. You can call it, and it will do
whatever you override it to do, but the object will not be deallocated.
You're thinking of it backwards. Instead of finalize() destroying the
Object, when the JVM destroys an object it does something like:

doGC(Object o)
{
 try {
   o.finalize();
 } catch (RuntimeException e) {
   /* ... Invoke complex error handling (i.e. ignore) ... */
 }

 /* ... Last check object has no references and so on ... */

 /* ... Do the actual work of destroying the object ... */
}

(p.s. before everyone jumps on that, it's a SIMPLIFIED PARAPHRASED
EXAMPLE :) )

Of course, although there is no way to directly stop an Object being
deallocated from finalize(), there is a trick - simply assign a
reference to the object somewhere. That way, finalize returns, and when
the JVM does it's 'last check' it finds the reference, and the object is
retained. This is part of the reason finalize is dangerous.

Cheers,
Ross

Signature

  [Ross A. Bamford]     [ross AT the.website.domain]
Roscopeco Open Tech ++ Open Source + Java + Apache + CMF
http://www.roscopec0.f9.co.uk/ + info@the.website.domain

Patricia Shanahan - 28 Apr 2005 13:54 GMT
...
> An exception handled within a constructor is a regular exception, but
> one thrown by a constructor *should* result in the object not being
[quoted text clipped - 27 lines]
> 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
Ross Bamford - 28 Apr 2005 16:32 GMT
> ...
> > An exception handled within a constructor is a regular exception, but
[quoted text clipped - 83 lines]
>
> Patricia

That surprised me to begin with, but now I think more on it I realise
it's absolutely the only way it could work - I was falling into the
"Exceptions are special" trap myself there I think, or maybe
thinking++ :)

I guess from the day-to-day programmer perspective, it doesn't really
matter unless you're keeping extra references like above, the effect is
the same (?), but then it's one of those situations where you innocently
do keep a reference one time and end up chasing the same bug for days ;)

I'll filter out the dumb posts in future before they get out ;>

Cheer,
Ross

Signature

  [Ross A. Bamford]     [ross AT the.website.domain]
Roscopeco Open Tech ++ Open Source + Java + Apache + CMF
http://www.roscopec0.f9.co.uk/ + info@the.website.domain

Patricia Shanahan - 28 Apr 2005 17:24 GMT
> I guess from the day-to-day programmer perspective, it
> doesn't really matter unless you're keeping extra
> references like above, the effect is the same (?), but
> then it's one of those situations where you innocently do
> keep a reference one time and end up chasing the same bug
> for days ;)

I think the main conclusion for everyday programming is
that, if you must register an object with its class or
another object from the constructor, that should be the very
last thing the constructor does, after anything else that
might possibly throw an exception.

Of course, if the object's class is non-final, there is
still the problem of subclass constructor bodies that run
after the end of the superclass constructor.

A better solution is to treat registration of objects as a
separate action, and limit the constructor to building the
object's own state.

Patricia


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.