wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Exceptions raised in catch block code 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 "Exceptions raised in catch block code" Watch "Exceptions raised in catch block code" New topic
Author

Exceptions raised in catch block code

Kitty Dayal
Ranch Hand

Joined: Jul 22, 2004
Posts: 89
Hi all,

What will happen to exceptions raised in catch block. Will it be executed or not.

My doubt raises from these snippets of code:

First: (This one from jdiscuss mock exam)

Answer given: m1 Starts 1 4

Why will it not print 2.
Since both NullPointerException & IndexOutOfBoundsException are runtime, why then only one gets raised and not the other?

Second:

Answer: compile error exception never thrown in the try body.

Should checked exception only be thrown from try block?

Also an exception thrown in finally block: "MUST" be in a try-catch/finally block(even if it is an runtime). Is this true ? because the following block does not compile:



If i add try/catch around it then it compiles fine.

Sorry for being too lengthy.. I am confused a bit regarding these concepts..


Thanks,
-Kits
Peter den Haan
author
Ranch Hand

Joined: Apr 20, 2000
Posts: 3252
Originally posted by Kitty Dayal:
What will happen to exceptions raised in catch block. Will it be executed or not.
They will be thrown. But because you are out of the try block by now, they won't be caught (unless there is another try block around the whole thing).
Why will it not print 2.
Because there is no NullPointerException thrown inside the try block.
Should checked exception only be thrown from try block?
No, but any checked exceptions that you don't catch must be declared in the method's throws clause. The main() method does not have a throws clause and therefore there cannot be any uncaught checked exceptions.

Also an exception thrown in finally block: "MUST" be in a try-catch/finally block(even if it is an runtime). Is this true ?
Probably not, although I don't really understand what you're trying to say but it looks wrong. The code you list does compile, but you declare a MyException which isn't being used so I guess the code you tried has problems with non-runtime exceptions which are neither being caught nor listed in a throws clause.

- Peter
Ning Du
Greenhorn

Joined: Jul 08, 2003
Posts: 11
Kitty,

Maybe the third snippet can not compile just because you had an extra clause()"System.out.println("END");" after the "finally" clause.If not, it correctly compiles.


SCJP1.4
 
jQuery in Action, 2nd edition
 
subject: Exceptions raised in catch block code
 
Similar Threads
Too many exceptions?
Try/catch flow???
try/catch??
exception dilema
Exception problem.