I have a static method that throws an exception, but I am unable to declare the exception at that method. I get a compile errror in main():
unreported exception Exception; must be caught or declared to be thrown
then I delcare the exception at main() (where the errant method is called), and it compiles and runs fine. Why is my declaration at the method that actually throws the exception not accepted? I know if the exception is not handled where it is thrown, then the exception object is passed to the next method on the stack, but why does it get passed?
You can have a method which does not throw an Exception, but you can declare it as throwing an Exception. Now any method calling it has a method which claims to throw a checked Exception. You must do something with that Exception, either catching it or declaring it and passing the Exception on to the next method.
Joined: Apr 07, 2011
Throwing an exception is a requirement of the assignment.
>>You must do something with that Exception, either catching it or declaring it and passing the Exception on to the next method.
So you're saying that I either declare it (which causes it to be passed to the next method) OR handle it right there, but not both declare it AND handle it right there? OK, so I passed it to main() and the handler in toInt wasn't used and main() had no way to deal with it. I think I get it now.
Thank you both!
Joined: Oct 13, 2005
Well done getting it
You will have to try both declaring and catching an Exception in the same method. I think you can fool the compiler into accepting both, at least for an instance method which you might override.Bruce Eckel in Thinking in Java 4th edition says that lying about what a method throws is about the only thing you can fool the compiler with about Exceptions. The reason is that an overridden version of that method might really want to throw an Exception of some sort or other.
This is one of the very few circumstances where throws Exception rather than throws SomeSpecificKindOfException is good practice.