aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Reg. Exceptions in finally block Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Reg. Exceptions in finally block " Watch "Reg. Exceptions in finally block " New topic
Author

Reg. Exceptions in finally block

Angela Narain
Ranch Hand

Joined: Apr 14, 2001
Posts: 327
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

Joined: Apr 02, 2001
Posts: 1157
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

Joined: Apr 06, 2001
Posts: 371
Why isn't the exception handling be given to JVM right at where m2() was invoked?
Desai Sandeep
Ranch Hand

Joined: Apr 02, 2001
Posts: 1157
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).]
 
 
subject: Reg. Exceptions in finally block