Hi Tim (and Elji),
Sorry, I started a new job this week, and travelled halfway around the world to do so. So I have not been paying enough attention in this forum, and missed this question when it was originally posted.
Elji - you are correct. You do not
have to declare the RuntimeExceptions in your method signature, but doing so does not hurt either. You will still have implemented the interface, without changing the interface in any way.
Consider the following code:
This code will compile and run quite happily, even though my interface's method signature does not include the RuntimeException. And just declaring it in my implementation does not mean that it must now be caught in the calling method - as you can see, my main() method does not acknowledge the RuntimeException at all.
Where it does make a difference is in the JavaDoc. By declaring it in the JavaDoc comments of the code, I get the following in my JavaDoc:
If I hadn't declared it in my signature and JavaDoc, I would have only had:
Nowhere near as useful for the developer trying to use your methods!
Note that according to the "
Documenting Exceptions with @throws Tag" section of "
How to Write Doc Comments for the Javadoc Tool", "
By convention, unchecked exceptions should not be included in a throws clause.". I have contradicted this in the book, suggesting that it can be beneficial to declare the checked exceptions in the throws clause, especially in the case where you are working around a limitation of the provided interface's API and your code may be used in an
IDE. For example, if I am using Eclipse, I can create the following bit of code:
Eclipse will then warn me that I have unchecked exceptions, and ask me what I would like to do - add them to my method signature or create a try ... catch block for them.
IF I have declared the unchecked exception in my throws clause, I will get the following code if I tell Eclipse to create the try...catch blocks:
Personally, I consider that to be extremely valuable.
I am not advocating this in
all cases where you might use a RuntimeException. A classic case for not doing this is something where you really
need the application to stop running before something really bad happens. But in the specific case of the undesirable RuntimeExceptions being used in the
SCJD assignments we might be justified in adding the uncaught exception to the throws clause.
Since this is going against standard programming practice (or at least, Sun's standard practices
), I made the following comment in the book:
If you do list the RuntimeException in the method signature and/or the Javadoc, it would be wise to add a code comment stating why you did this for the benefit of the person who is maintaining your code. In the specific case of the Sun assignment, you might also want to consider putting a comment in the Javadoc itself stating why you did it.
Hope this helps.
Regards, Andrew
[ February 18, 2006: Message edited by: Andrew Monkhouse ]