Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

try and catch

 
Karu Raj
Ranch Hand
Posts: 481
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why is the return 1 is not printed at all ???

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;
}
}
}
 
Karu Raj
Ranch Hand
Posts: 481
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi

when i compile the above code
I am getting error as below

---------- Javac ----------
warning: finally clause cannot complete normally
}
^
--------------------------------------------------------
 
harish shankarnarayan
Ranch Hand
Posts: 158
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hey its compiles fine

in the above example first its returning value 1.
after that as finally executes always its returning 3
and u r getting the output 3
remove finally u will get output 1.

i hope so u got it..
 
Veer Batra
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It works for me and output is 3.
 
Karu Raj
Ranch Hand
Posts: 481
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi all
I am using jdk 1.4
 
Raghusham Sankargal
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
Its a warning not an error. Did you try java <class-name>. Tell me if you get the error. I don't think you should get.
 
Vijayagopalan Raveendran
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
finally block is executed irrespective of whether exception is thrown or not.
 
Vijayagopalan Raveendran
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
finally block is executed irrespective of whether exception is thrown or not.
 
Gyan Shankar
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The finally return always overrides the try return
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic