• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why use 'throws' if it there's try statement in main?  RSS feed

 
Winston Liek
Ranch Hand
Posts: 194
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Whats the difference between:
1. DO NOT INCLUDE 'throws' from the method that will cause exception then include a try statement from the method caller
2. INCLUDE 'throws' from the method that will cause exception then include a try statement from the method caller

Both of the process will go to catch statement from the main method.


--------------------------------------------------------------------------------------------

---------------------------------------------------------------------------------------------

Caller method:

 
Campbell Ritchie
Marshal
Posts: 56584
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You do not need a throws for an unchecked Exception. In most cases unchecked Exceptions need alteration to the code, but let's pretend it is an Exception you ought to catch

The thing about Exceptions is you should always consider what you are going to do if it occurs
What are you going to do if the Exception occurs in the same method? Can you get different input or try something different or repeat the procedure and expect it to work without an Exception? If you can get it to work without Exceptions by trying again, then you should be catching the Exception there. If not, then you should propagate it. A throws tells the calling methods that this method might not work, and you must be prepared to handle the Exception. If it is a checked Exception, the javac tool will verify that all possible calling methods deal with that Exception, but it ignores unchecked Exceptions.
Crappy little example where you can have an Arithmetic Exception and still try again:-
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!