This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
(1) Compilation error (2) Runtime error (3) Compile successfully, nothing is printed (4) Inside throwMethod. followed by caught: java.lang.IllegalAccessExcption: demo
My answer is (4). Because exception which is thrown in throwMethod() will be caught by catch and it displays �Inside throwMethod. followed by caught: java.lang.IllegalAccessExcption: demo�. But the answer is (1). Can anyone clarify me?
See the throws keyword tells to the complier that "I know the throwMethod() is risky and it throws IllegalStateException". By doing this you don't have to handle the exception as it occurs. When the exception is thrown the control goes to the calling method...
When you do throw new IllegalAccessException("demo") a new exception is thrown and the control goes to the caller method where it is handled and the message is printed inside catch...
But when you comment the line no new exception is thrown and the execution is completed without any exception...
if i remove try,catch,finally in main method it is showing a compilation error.
If you remove try,catch from the main method and an exception is thrown...the exception might be saying exception is not handled by your code. As i said when an exception occurs either you handle it or declare it...
If the exception occurs and you declare it but not handle it the execution is sent back to the caller method...which in turn is supposed to handle the exception....In your case the main() is the caller...So execution is ducked to main() from the risky method...And in main() the compiler finds that neither have you handled the exception nor have you declared it. Hence the compilation fails. [ December 04, 2008: Message edited by: Sudipto Shekhar ]
Joined: Feb 28, 2007
By declaring an Exception, its not necessary that you must throw the exception. But compiler wont escape if you are throwing a checked exception without declaring or handing it with try catch.