• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Reg. Exceptions in finally block

 
Angela Narain
Ranch Hand
Posts: 327
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class NewException extends Exception {}
class AnotherException extends Exception {}
public class A {
public static void main( String[] args ) throws Exception
{
try
{
m2()
}
finally { m3() ; }
}
}
public static void m2() throw NewException { throw newException(); }
public static void m3() throw AnotherException { throw AnotherException(); }
ANS : It will compile but throw AnotherException when run
What i have understood :
Now m2() has no catch block, but as it declared in the throws clause, it is passed
to the default exception handler. The finally block will definitely get executed,
but will not be caught so as it is passed on to the default exception handler
it will at run-time give AnotherException .
Pls correct me if wrong .Can me someone explain the output .
 
Desai Sandeep
Ranch Hand
Posts: 1157
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Anjela,
Since you have defined the main method to throw Exception, you donot need to use try..catch block to catch the exceptions thrown by methods m2() and m3().
Hence this class compiles properly.
When run the contents of m2() and m3() are executed The control is given to default error handler of JVM only after executing m3() of the finally block.
Normally when an exception is thrown the control is back to JVM.The exception thrown at execution of m2() and m3() is wrapped in some format and is then given to the JVM.
If you modify the code as follows and look at the stack trace you would realize this is what is happening.

The output of this code snipplet is :

Note that the exception is raised at m2() and m3() both.However the control is not given to the JVM until m3() gets executed.
Hope this helps,
Sandeep
SCJP2, OCSD(Oracle JDeveloper), OCED(Oracle Internet Platform)
[This message has been edited by Desai Sandeep (edited August 29, 2001).]
 
Cameron Park
Ranch Hand
Posts: 371
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why isn't the exception handling be given to JVM right at where m2() was invoked?
 
Desai Sandeep
Ranch Hand
Posts: 1157
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Cameron,
Originally posted by Cameron Park:
Why isn't the exception handling be given to JVM right at where m2() was invoked?

The control will be given to JVM only after finally block has been executed, irrespective of exception being thrown in the try block.
-- Sandeep
[This message has been edited by Desai Sandeep (edited August 29, 2001).]
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic