Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Java Exception

 
Aarif Diwan
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
i am confused with this prblm.
========================================
public class Test1{
public static void main(String args[]){
System.out.println(method());
}
public static int method(){
try{
return 1;
}
catch(Exception e){
return 2;
}
finally{
return 3;
}
}
}
What will be the output?
A1 1
A2 2
A3 3
A4 0
========================================
If i am running this on java "1.4.2_03" version it gives Compile time error.
"Test.java:14: warning: finally clause cannot complete normally
}
^
1 warning"

and on version 5.0 it's output is "3"
WHYYYYYYYYYYYYYYYYY???
----------------------------
Thnx in advance
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Eric,

Welcome to JavaRanch!

First, a bit of business: you may not have read our naming policy on the way in. It requires that you use a full, real (sounding) first and last name for your display name. A single name, nicknames, "handles", and cute punctuation aren't acceptable at the Ranch. You can change your display name here. Thanks!

To answer your question: returning from a finally block is a very bad practice that's what the compiler warning (not error, warning; the compiles and will run fine) is telling you. If you return from finally, then any return value from the try or catch block, and any thrown exceptions, will be lost. It's confusing and almost always the wrong thing to do.

Under both JDK 1.4 and 1.5, it will run and print "3".
 
Ramasubbhu Allur Kuppusamy
Ranch Hand
Posts: 120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Eric,

Welcome to Javaranch!

The hard and fast rule is "Finally block runs, no matter what!".
But for a return statement in the finally block, the control would have returned the value 1 in the try block.

As EFH rightly pointed out, embedding return statement in finally block is not a good programming practice. You can always experiment to learn "Java Rules', though .
 
Aarif Diwan
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank U sheriff and Ram.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic