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.
above is a snippet from the K&B book. There's a thumb rule saying "any method that throws a checked exception or invokes a () that throws a checked exception, must either declare it or put the () in a try/catch"
dostuff() is declaring the checked exception by saying "void doStuff() throws MyException "
so could I say that the code would have compiled had the calling () been so :-
Netty, In both the cases you have to use MyException instead of IOException. The reason being you always try to catch Exception that is being thrown. According to your code doStuff() throws MyException. So that should be the one you should be catching. Keep in mind that MyException extends Exception and not IOException( IOException being a subclass of Exception). So you cannot catch IOException in the places where MyException is caught. The compiler complains that IOException is never thrown in scope. You could otherwise say something like
This is valid because MyException is subclass of Exception and not IOException. Hope this clears your doubt.
Also note that if you're catching multiple Exception types, then catch blocks for the most specific types (that is, the "most extended" subclasses) must appear before the parent types. Otherwise, the exception will be caught by the superclass catch block, leaving you with unreachable code (the subclass catch blocks) that will cause a compile-time error.
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer sscce.org
Joined: Sep 20, 2004
Kali, Marc, Anurag Thanks for the lifeline...again. For the time being this one gets canned !