Dear Ranchers, When we write some code in try block then we provide a catch block(or declare exception in the method signature). My Question is if exception has already been caught in the catch block then why again rethrowing the same exception in catch block and declare the exception in the method signature.
you can throw a new excpetion or rethrow the same exception in catch or finally block..but the rule says you have to both handle AND declare that exception.. but what actually your confusion is??? [ July 25, 2007: Message edited by: Priyam Srivastava ]
"History would be kind to me, for I intend to write it."
Consider JVM as an old lady. Consider the try block as a strong guy. The strong guy is trying to hit the old lady with a ball. But catch who's a good guy catches the ball and saves the lady. Now the good guy catch turns bad and decides to throw either the same or any other ball to the old lady. You need to save the lady now. Because our previous catch has turned bad we need some other good soul to save the lady. That other good soul would be either specified using throws or what you can do is define a nested try catch in the good turned bad catch and throw the new ball in this nested try and catch it in the nested catch.
Many thanks Nitish.
Also I wasn't clear why there are two parallel mechanisms, try and catch, and throwing.
But I've just realised that if you are creating your own exception classes, you would have to use THROW, as they they are not integrated in the JVM runtime - is that right?
No, not really. The entire point of an exception class is that something is going to throw an instance of that class. It doesn't matter whether you write code which throws an exception, or whether I write it, or whether some employee of Sun writes it. It's all Java code and it all follows the same rules. There's no difference between the java.io.File class throwing an IOException and your class throwing a YourException.
Hi Paul, thanks for your response. I haven't got this yet - sorry. If you can test exceptions with try and catch; those are conditions, possible loopholes in your code that could crash your program, and you are testing specifically for those. Where do throws fit it & why do you need that mechanism as well? - Is it a broader net, for wider categories of things that could go wrong?
As i told we need to declare the checked expection....that declaration is done by "throws" keyword. Well this declaration is for whoom hmmmm for the compiler as it checks the function and sees and thus compiler makes the programmer to have a try catch block for a method throwing the checked exception. Have you wondered why this happens and how it happens i.e always have a handler for a method throwing a checked exception and how does the compiler comes to know that it throws a checked exception... that is through the declaration "throws"
[ SCJP 6.0 - 90% ] , JSP, Servlets and Learning EJB.
Try out the programs using a TextEditor. Textpad - Java 6 api