• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

finally block with return statement

 
saiprasad raut
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

please go through the below code



The ArithmaticException thrown in the computeAverage() method anpropogated to the printAverage() method is nullified by the return statement in the finally block.

Why is it so ? why does return in finally block nullifies the exception? is it only for unchecked exceptions?

Thanks,
Saiprasad
 
Ana Abrantes
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, that's because it's an unchecked exception.
But if you had a catch statement you could have caught that runtime exception.
 
David Ng
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't believe the type of exception matters. If a return is executed within a finally block, it will nullify all exception (including pending one). After control is retuned to the calling method, execution will continue as normal.

The program below will run to normal completion and prints "Normal termination".

However, if line 20 is removed or commented out, it will terminate with the following:

My Exception
at Q0001Exception.method(Q0001Exception.java:15)
at Q0001Exception.main(Q0001Exception.java:7)
Exception in thread "main"

 
savas karabuz
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

The following page clarifies the situation, i think :

JAC_061: Do Not Return From Inside A try Block (High)

Also, jdk1.4 javac compiler should issue a warning in such a situation.

...Savas...
[ May 27, 2004: Message edited by: savas karabuz ]
 
tangi
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
guys,
m getting compile error when i try to return from finally. Execution is not getting continued at any point of time
says---finally clause cannot complete normally
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
tangi,

Welcome (back) to JavaRanch!

We ain't got many rules 'round these parts, but we do got one. Please change your display name to comply with The JavaRanch Naming Policy.

Thanks Pardner! Hope to see you 'round the Ranch!

----

If you've a compiler error you're trying to address, I'd suggest posting a question in the Beginners forum, including the code that you're trying to compile and the exact error message you're getting.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic