阅读更多
Everyone tries to avoid them, but it's an unfortunate fact:
Errors occur in software programs. However, if you handle errors properly, you'll greatly improve programs' readability, reliability and maintainability. The Java programming language uses exceptions for error handling.
What Is an Exception?
An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions.
The Catch or Specify Requirement
There are two kinds of exceptions: checked exceptions and un-checked exceptions.
it is the bottom line guildline:If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.
Best Practices for Designing the API
1.When deciding on checked exceptions vs. unchecked exceptions, ask yourself, "What action can the client code take when the exception occurs?"
Moreover, prefer unchecked exceptions for all programming errors: unchecked exceptions have the benefit of not forcing the client API to explicitly deal with them. They propagate to where you want to catch them, or they go all the way out and get reported.
2.Preserve encapsulation.
Never let implementation-specific checked exceptions escalate to the higher layers. For example, do not propagate SQLException from data access code to the business objects layer. Business objects layer do not need to know about SQLException. You have two options:
>Convert SQLException into another checked exception, if the client code is expected to recuperate from the exception.
>Convert SQLException into an unchecked exception, if the client code cannot do anything about it.
a recommended way is:
public void dataAccessCode(){
try{
..some code that throws SQLException
}catch(SQLException ex){
throw new RuntimeException(ex);
}
not:
public void dataAccessCode(){
try{
..some code that throws SQLException
}catch(SQLException ex){
ex.printStacktrace();
}
}
for the last one, client can do nothing, so we can throw it to upper tier to let him/her know what had happened.
3. how to throw exceptions?
for those checked exceptions, such as Integer.parseInt("ABC"), I/O exception. we can catch it on the business level, deal it with a default manner or throw it to the upper tier(by convert it to a recognised exception) which have the ability to deal with it.
for those unchecked exceptions, throw it to upper tier to deal with.