File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Propagating and Catching an exception problem 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 "Propagating and Catching an exception problem" Watch "Propagating and Catching an exception problem" New topic

Propagating and Catching an exception problem

Mohit G Gupta
Ranch Hand

Joined: May 18, 2010
Posts: 634

by Katherine Sierra (Author), Bert Bates (Author)
exerCise 5-3

In this exercise you're going to create two methods that deal with exceptions. One of
the methods is the main() method, which will call another method. If an exception
is thrown in the other method, main() must deal with it. A finally statement will
be included to indicate that the program has completed. The method that main() will call will be named reverse, and it will reverse the order of the characters in a
String. If the String contains no characters, reverse will propagate an exception up
to the main() method.
---- Create a class called Propagate and a main() method, which will remain
empty for now.
---- Create a method called reverse. It takes an argument of a String and
returns a String.
---- In reverse, check if the String has a length of 0 by using the
String.length() method. If the length is 0, the reverse method will
throw an exception.
----Now include the code to reverse the order of the String. Because this isn't
the main topic of this chapter, the reversal code has been provided, but feel
free to try it on your own.

String reverseStr = "";
for(int i=s.length()-1;i>=0;--i) {
reverseStr += s.charAt(i);
return reverseStr;
---- Now in the main() method you will attempt to call this method and deal
with any potential exceptions. Additionally, you will include a finally
statement that displays when main() has finished.

Is this solution correct ?

OCPJP 6.0 93%
OCPJWCD 5.0 98%
Ankit Garg

Joined: Aug 03, 2008
Posts: 9463

1. The indentation makes the code very hard to understand. Try to indent your code properly.
2. The part which checks the length of the String and throws an exception should be in the reverse method not the main method. Then you have to call reverse method in a try-catch block (the try catch block will also have a finally block)...

SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Ninad Kulkarni
Ranch Hand

Joined: Aug 31, 2007
Posts: 802


Ankit is correct
In your code the thrown Exception caught by main method that is not propogated.

SCJP 5.0 - JavaRanch FAQ - Java Beginners FAQ - SCJP FAQ - SCJP Mock Tests - Tutorial - JavaSE7 - JavaEE6 -Generics FAQ - JLS - JVM Spec - Java FAQs - Smart Questions
I agree. Here's the link:
subject: Propagating and Catching an exception problem
It's not a secret anymore!