Handling Errors Using Exceptions

Everyone tries to avoid them, but it's an unfortunate fact: [b]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.[/b]
[b]What Is an Exception?[/b]
An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions.

[b]The Catch or Specify Requirement [/b]
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.

[b]Best Practices for Designing the API[/b]
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.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值