jQuery in Action, 3rd edition
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Too many exceptions? 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 "Too many exceptions?" Watch "Too many exceptions?" New topic

Too many exceptions?

sonir shah
Ranch Hand

Joined: Nov 01, 2001
Posts: 435
Q: What is wrong with the following code?
class MyException extends Exception {}
public class TestClass
public static void main(String[] args)
TestClass tc = new TestClass();
catch (MyException e)
public void m1() throws MyException
throw new MyException();
public void m2() throws RuntimeException
throw new NullPointerException();
Options :
1)It will not compile because you cannot throw an exception in a finally block
2)It will not compile because you cannot throw an exception in a catch block
3)It will not compile becuase NullPointerException cannot be created this way
4)It will not compile
5)It will compile but will throw an exception at Runtime
I tried runnig the program but it is giving me some kind of error, which I cannot understand.
Can any one let me know the correct output?
Stefan Zoerner
Ranch Hand

Joined: Nov 29, 2001
Posts: 121
Hello Sonir!
Compile the following code. It is yours, except that a throws-phrase is added to main.

It compiles fine and shows you, that answers 1)-3) are wrong. The things described in the 3 options are in the code as before, and are generally legal.
Without the throws, the main-method could throw an MyException (position marked with // (1)), that is not handled in the method body via try/catch, and not declared in the header of the method (throws ....). Because MyException is a subclass of Exception, this is not legal, and that is what the compiler says:
TestClass.java:13: unreported exception MyException; must be caught or declared to be thrown
So answer 4) is correct.
See any Java Book, Chapter Exception Handling, for further details,
[ January 11, 2002: Message edited by: Stefan Zoerner ]

Stefan Zoerner
Author of German LDAP-Book
Committer at Apache Directory Project
Ragu Sivaraman
Ranch Hand

Joined: Jul 20, 2001
Posts: 464
Always remember one thing.. If you have a checked exception. IT MUST BE HANDLED..
Inside the catch{} you call a method that throws an exception which is not handled.. That's the reason compiler is complaining.. Whereas inside finally{} things are ok.. why? its becoz it throws an runtime exception..
The programmer is not obliged to handle it..
just comment the method out in the catch block you will see
Have fun coding
I agree. Here's the link: http://aspose.com/file-tools
subject: Too many exceptions?
It's not a secret anymore!