File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Propogating Exceptions - Exercise5.3 in K&B

 
Esther Kak
Ranch Hand
Posts: 51
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 537
Eclipse IDE Java Python
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Esther Kak
Ranch Hand
Posts: 51
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 385
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Esther Kak
Ranch Hand
Posts: 51
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It worked thanks.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic