I have banged out a working program for OOP2, but I am stuck at the Exception part. When I try to compile, I get the message that java.lang.Exception must be caught, or it must be declared in the throws clause of this method. int a = NLM.toInt( x ); The little insert character mark points to the opening parenthesis. I have declared the method just as the instructions specified, and I put a try catch statement in the body of the method. What am I doin' wrong?
I am not sure but it sounds like you have the code to catch the exception and now you need the code to throw the exception if certain criteria have not been met in the method. I don't know how much more I can tell, plus I don't know if I am exactly right yet as I have not been nitpicked on this one yet. Good Luck
"Happiness is a way to Travel, <b>Not</b> a Destination" -- Unknown
Carol, it sounds like your method is saying I'm going to throw an exception, but the method is handling the exception not throwing it. You would need a throw clause within the catch() so that the exception can be thrown from the method. Maybe this will help. A thrown exception can be passed (relayed) up through the calling methods until it is actually caught (handled). Each method that throws an exception or passes an exception through it, is required to have throws SomeException.
This will cause the error because you have stated that the method will throw an exception back to the calling method, but the method is not throwing an exception it is handling it. To correct you would have to add a throw clause within the catch or remove the throws SomeException from the method's signature (throws SomeException is not actually part of the signature, read that some where). A method that calls another method that has throws can pass on the thrown exception without re-throwing or handling the exception:
Notice that the exception passes through methodA() without being caught or re-thrown. methodA() is still required to have the throws SomeException since it throws the exception thrown to it from methodB() back to main() to be handled. Hope this helps
posted 18 years ago
Doh!!! I put the try catch clause in the method which throws the exception, instead of putting the code which calls the exception-throwing method inside a try catch clause. Does that make any sense? It was very late at night........... Thanks for your responses!
Won't you please? Please won't you be my neighbor? - Fred Rogers. Tiny ad: