aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Propogating Exceptions - Exercise5.3 in K&B 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 "Propogating Exceptions - Exercise5.3 in K&B" Watch "Propogating Exceptions - Exercise5.3 in K&B" New topic
Author

Propogating Exceptions - Exercise5.3 in K&B

Esther Kak
Ranch Hand

Joined: Oct 11, 2006
Posts: 51
How do I make the reverse() method throw unhandled exception when called in main(). According to the exercise question, the method should not handle exception in the reverse method but pass it to the main method and throw it there. The method should throw an error when the string length is 0.
Here is my code.
Nitish Bangera
Ranch Hand

Joined: Jul 15, 2009
Posts: 537

use the "throw" keyword and throw the exception. If its checked exception then declare it using the "throws" keyword in the definition of reverse method and handle it in the main method using try and catch.


[ SCJP 6.0 - 90% ] , JSP, Servlets and Learning EJB.
Try out the programs using a TextEditor. Textpad - Java 6 api
Esther Kak
Ranch Hand

Joined: Oct 11, 2006
Posts: 51
Thanks for the reply....but still could not get it. For the above code, if the length of the string is zero, the reverse() method should throw an exception. That exception should be propogated to the main method. When the exception encountered at run time, it should throw a run time exception. How do I fix the code. Please help. Thanks in advance.
Siva Masilamani
Ranch Hand

Joined: Sep 19, 2008
Posts: 385
use throw new RuntimeException("Thrown from reverse method") inside the if loop

basic exception concept

when you are throwing checked exception you should either handle that exception inside the try/catch block or declare the method that throws checked exception .e.g. void methodName() throws CheckedException.

If you are calling a method that throws checked excpetion then that method call should be from try/catch block of the calling method ot the calling itself should be declared to duck that exception.

Also when you try to handle or duck the checked exception the block should contatin code that may throw checked exception else you will get compile time error.

But the above rules are not applicable to RuntimeException.It is not ncessary to catch or duck the RuntimeException.

FYI

Anything that extends Exception is checked and anything that extends RuntimeException are unchecked exception.


SCJP 6,SCWCD 5,SCBCD 5

Failure is not an option.
Esther Kak
Ranch Hand

Joined: Oct 11, 2006
Posts: 51
It worked thanks.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Propogating Exceptions - Exercise5.3 in K&B