- Java Exception Handling
- Basic try-catch-finally Exception Handling in Java
- Java Try With Resources
- Catching Multiple Exceptions in Java 7
- Exception Hierarchies
- Checked or Unchecked Exceptions?
- Exception Wrapping
- Fail Safe Exception Handling
- Pluggable Exception Handlers
- Logging Exceptions: Where to Log Exceptions?
- Validation - Throw Exceptions Early
- Validation - Throw Exception or Return False?
- Exception Handling Templates in Java
- Exception Enrichment in Java
- Execution Context
Validation - Throw Exceptions Early
When receiving input that needs to be validated before it can be used, validate all input before using any of it. You should 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.