jQuery in Action, 3rd edition
The moose likes Beginning Java and the fly likes Java Exception Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Java Exception" Watch "Java Exception" New topic

Java Exception

Aarif Diwan

Joined: Jun 21, 2006
Posts: 2
i am confused with this prblm.
public class Test1{
public static void main(String args[]){
public static int method(){
return 1;
catch(Exception e){
return 2;
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"
Thnx in advance
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

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

[Jess in Action][AskingGoodQuestions]
Ramasubbhu Allur Kuppusamy
Ranch Hand

Joined: Sep 16, 2005
Posts: 120

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 .

Regards,<br />Ram.<br />SCJP 1.4
Aarif Diwan

Joined: Jun 21, 2006
Posts: 2
Thank U sheriff and Ram.
I agree. Here's the link: http://aspose.com/file-tools
subject: Java Exception
It's not a secret anymore!