|Java Exception Handling|
|Introduction to Java Exception Handling|
|Basic Try Catch Finally|
|Catching Multiple Exceptions|
|Checked or Unchecked Exceptions?|
|Fail Safe Exception Handling|
|Pluggable Exception Handlers|
|Logging: Where to Log Exceptions?|
|Validation: Throw Exceptions Early|
|Validation: Throw Exception or Return False?|
|Exception Handling Templates|
When receiving input that needs to be validated before it can be used, validate all input before using any of it. You whould not change any state in the application or attached systems until all input data has been validated. That way you avoid leaving the application in a half valid state.
For instance, in a DAO method that inserts a user and an address into two different tables in a database, do like this:
check if user already exists validate user validate address insert user insert address
Do not do like this:
check if user already exists validate user insert user validate address insert address
If you do like this, and the address turns out to be invalid you will still have inserted the user in the system. What happens when the user corrects the address and retry registering? He will be told that his user already exists, right?
The problem is not only related to database insertions. In general, validate all input before using any of it, to avoid leaving the application in a half valid (=unknown) state.