• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Exception

 
Ranch Hand
Posts: 135
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I have a doubt on following program.

package chapters.chap02;
public class Ques04 {
public static void main(String[] args) {
System.out.println(test1());
}
static int test1(){
if (test2() == -1)
{
try{
throw new Exception("test1");
}catch(Exception e){
return 5;
}finally{
return 3;
}
}else{
return 6;
}
}
static int test2(){
if (true){
try{
throw new Exception("test2");
}finally{
return -1;
}
}else{
return 9;
}
}
}

In test2(),an exception is thrown.But where it is handled?The program compiles And run successfully and produce output as 3.
Please suggest me.
Thanks in advance.
 
Sheriff
Posts: 22784
131
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It kind of surprises me a bit that it compiles, but after a bit of testing I found out why.

A finally block will always get executed*. Therefore, the "return -1" will overrule the exception that is thrown. Remove that return statement and the compiler complains that Exception must be caught or thrown.


* provided there is no System.exit, JVM crash or other unrecoverable error such as the PC dying.
 
reply
    Bookmark Topic Watch Topic
  • New Topic