This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
I am trying to learn about exception handling and am having a hard time getting my mind around the big picture. Can I get some feedback on the code below. Should the throws have DataNotFoundException, AccessDeniedException AND the try catch with each message defined? Or is it ok to just have throws Exception and each of the additional exceptions in the try catch.
Is there a better or cleaner way to write these exceptions than the way I have below?
For checked exceptions, you need either a "throws" clause in the method declaration (line 11), or you need to catch the exceptions and handle them - not both.
The "throws" clause just means: this method might throw this exception. If you're catching those exceptions inside the method (and not throwing them further), you don't need the "throws" clause.
In general, specifying "throws Exception" (explicitly saying that the method can throw any kind of exception) is bad practice. A "throws" clause should be as specific as possible about what exceptions it throws. If you declare your method with "throws Exception" then the users of your method are forced to deal with any kind of exception that might happen, which will make it harder for them to handle errors.