• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Exception

 
Vinal Kalyan
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can you please explain why the exception in a() is not thrown up the call Stack and caught by the catch block in the main method. Instead, the method returns the Integer object and no exception is caught in the main method.

Class Test {
public static void main(String[] args) {
try {
Object obj = a();

catch (Exception e) {
System.out.println(e);
}

}
}

static Object a() throws Exception {
try {
throw new IOException();
}
catch (IOException e) {
throw e;
}
finally {
return new Integer(1);
}
}
}

Thanks

Vinal.
 
Akash Singhal
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The return from the finally block overrides any previous return values as well as it also overrides any exceptions thrown. Hence the exception thrown is overriden by the object returned from the finally Block..

Regards
 
Animesh Shrivastava
Ranch Hand
Posts: 298
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Related to the same question i have a small doubt:
If i change the method Object a() as:

Why am i not getting any compilation errors? shouldnt the method return something of type Object?

thanks
 
David Harkness
Ranch Hand
Posts: 1646
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Animesh Shrivastava:
Why am i not getting any compilation errors? shouldnt the method return something of type Object?
In this case the compiler can determine that an exception is always thrown from this code. Any statement after the try-catch block is unreachable under all conditions, so there's no need for a return.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic