File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

finalize question

 
mohamed hamdy
Ranch Hand
Posts: 72
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what will happen if a checked exception is thrown from the code of finalize() method when the object is to be garbage collected?
 
Francis Siu
Ranch Hand
Posts: 867
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi mohamed
what will happen if a checked exception is thrown from the code of finalize() method ?when the object is to be garbage collected?

Let me use some coding to point out what happen if a checked exception is thrown from the code of finalize() method ?

public static void main(String[] argv)
{
try
{
finalize();//(c)
}
catch(IOException ioE)
{
System.out.println("file point to null");//(d)
}
finally
{
System.out.println("Finish");(e)
}
}
public static void finalize() throws IOException
{
File file=null;
FileWriter fw =new FileWriter(file); //(a)
System.out.prinln("Arrive forest"); //(b)
}

if a checked exception is thrown from the code of finalize() method,
firstly,(a) exception occur,it will jump out the method and create the IOException object,so (b) is not excecuted
then,the IOException object catch from the catch IOException handler,so print
file point to null (d)
And the IOException object will be collected after this catch handler,then print
Finish (e)
If it is not clear,please post again
 
Francis Siu
Ranch Hand
Posts: 867
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
oo....
It may be easy to read

if a checked exception is thrown from the code of finalize() method,
firstly,(a) exception occur,create the IOException object and it will jump/throw out the method and terminate executing the remain part of programme
so (b) is not excecuted
then,the IOException object catch from the IOException handler,so print
file point to null (d)
And the IOException object will be collected after this catch handler,then print
Finish (e)
This time may be ok
 
Marlene Miller
Ranch Hand
Posts: 1392
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If an uncaught exception is thrown by the finalize method, the exception is ignored and finalization of that object terminates. Object API, finalize()
When I first read that sentence from the API, I thought it meant the finalize method ignored the exception. But the Java Programming Language says
This method is declared to throw any exception but if an exception occurs it is ignored *by the garbage collector*.
To find out what happens in the finalize() method I ran this test.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic