• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Exceptions raised in catch block code

 
Kitty Dayal
Ranch Hand
Posts: 89
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic