This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes exception handling Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "exception handling" Watch "exception handling" New topic
Author

exception handling

J Recker
Greenhorn

Joined: Aug 26, 2006
Posts: 18
I just ran the following code:



and the output is: Exception thrown
finally
after exceptions




I thought that after an exception is thrown, the catch will run, then finally, then it will exit the rest of the code. why does 'after exceptions' print out?

Thanks
E McKenney
Greenhorn

Joined: Sep 01, 2006
Posts: 18

Because once you catch the exception, execution flow resumes after the try-catch-finally block. That's also why you didn't have to declare your method with 'throws', because you handle the exception inside the method.

You'd only skip that last line if you didn't handle the exception that was thrown, or if you handled it but threw another one inside your catch block.


SCJP '06
Naseem Khan
Ranch Hand

Joined: Apr 25, 2005
Posts: 809
Originally posted by J Recker:
...
I thought that after an exception is thrown, the catch will run, then finally, then it will exit the rest of the code. why does 'after exceptions' print out?

Thanks


Remember when exception is caught, normal execution will continue. On the other hand, if suppose exception in uncaught, then it will be propagated to the method stack. In that case, after the execution of finally block, control will be returned to the caller and any line outside the try/catch/finally block will not be executed.


Naseem
[ September 06, 2006: Message edited by: Naseem Khan ]

Asking Smart Questions FAQ - How To Put Your Code In Code Tags
vRaj Verma
Greenhorn

Joined: Aug 21, 2006
Posts: 5
The try/catch/finally block is used to establish boundaries. Any code outside this boundary will always execute.
Burkhard Hassel
Ranch Hand

Joined: Aug 25, 2006
Posts: 1274
Hi cowboys,

J Recker wrote:
I thought that after an exception is thrown, the catch will run, then finally, then it will exit the rest of the code. why does 'after exceptions' print out?

It will execute the rest of the code. - After the try block.

BTW
You don't have to declare that myMethod throws an Illegal Arg. Exc. because it is a Runtime Exception.


Yours,
Bu.


all events occur in real time
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: exception handling
 
Similar Threads
Exception Handling
Exceptions
MindQ Q31
another question from MindQ Mock Exam
Question related to exception