• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Exception declaration not seen

 
Paul Berry
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?

Thanks,
Paul


 
Rameshwar Soni
Ranch Hand
Posts: 247
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think there is no need of writing try-catch block and also there is no need of throwing an exception. I tried your code the way it is below and it runs fine And the output is
 
Campbell Ritchie
Sheriff
Pie
Posts: 50278
80
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Paul Berry
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rameshwar,
Throwing an exception is a requirement of the assignment.

Campbell Ritchie,
>>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!
 
Campbell Ritchie
Sheriff
Pie
Posts: 50278
80
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic