File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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
Author

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();
try
{
tc.m1();
}
catch (MyException e)
{
tc.m1();
}
finally
{
tc.m2();
}
}
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?
Sonir
Stefan Zoerner
Author
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
tc.m1();
So answer 4) is correct.
See any Java Book, Chapter Exception Handling, for further details,
Stefan
[ 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
Sonir...
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
Ragu
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Too many exceptions?