Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

exception handling

 
J Recker
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 18
Chrome VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Naseem Khan
Ranch Hand
Posts: 809
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
vRaj Verma
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The try/catch/finally block is used to establish boundaries. Any code outside this boundary will always execute.
 
Burkhard Hassel
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic