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 refactoring my code and am in a mess in dealing with Exceptions in the correct way.
1. My read method throws a RecordNotFoundException which I created as a checked exception Do I need to catch the RecordNotFoundException in the read method itself if the record is not valid or simply stay with the throws clause and deal with the exception in the next layer - the business logic layer and again wrap the exception till it reaches the GUI layer when I actually deal with it? Shouldn't my Data class also work perfectly on its own displaying the exception messages as and when they occur?
2. While accessing the database file I throw IOExceptions and simply have wrapped them in my custom runtime exception - DatabaseException. So how do I deal with the DatabaseException in the next layer, as being a runtime exception it doesnot have to be caught?
1. your read method can throw RecordNotFoundException, not an issue. but you need to wrap this exception by user-friendly message when you show to user.
2. you need to handle all the exception whether it is runtime exception or checked exception. but one advantage of throwing a runtime exception is you need not to re-throw or catch in caller method[T which calls a Method E].
handling an exception is an important skill for a programmer.
My program throws checked exceptions, like the RecordNotFoundException, and runtime exceptions (IllegalArgumentException, DBException,...) from the Data class.
The checked exceptions are caught in my business service and there a (checked) business exception is throw. In my GUI I catch these checked exception and show an appropriate error message for the user (e.g. "room could not be found")
The runtime exceptions are not caught, because they indicate a developer's mistake (passing a null parameter to a method), not a user one. So that would be a bug in the program and should be not present anymore after testing the application.
Roel De Nijs wrote:The runtime exceptions are not caught, because they indicate a developer's mistake (passing a null parameter to a method), not a user one.
Hmm. but still you can declare RecordNotFoundException is a runtime exception rather than checked exception right ? we caught runtime exception to show error messages.
I prefer runtime exception mostly because, it wont force you to declare or catch the exception when you call a method which throws <edit>un</edit>checked exception.