博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Effective Java 59 Avoid unnecessary use of checked exceptions
阅读量:5110 次
发布时间:2019-06-13

本文共 1971 字,大约阅读时间需要 6 分钟。

The burden is justified if the exceptional condition cannot be prevented by proper use of the API and the programmer using the API can take some useful action once confronted with the exception.

ask yourself how the programmer will handle the exception.

   

Is this the best that can be done?

} catch(TheCheckedException e) {

throw new AssertionError(); // Can't happen!

}

How about this?

} catch(TheCheckedException e) {

e.printStackTrace(); // Oh well, we lose.

System.exit(1);

}

   

Principle

  1. If the programmer using the API can do no better an unchecked exception would be more appropriate. The checked nature of the exception provides no benefit to the programmer, but it requires effort and complicates programs.
  2. Turning a checked exception into an unchecked exception is to break the method that throws the exception into two methods, the first of which returns a boolean that indicates whether the exception would be thrown.
     

// Invocation with checked exception

try {

obj.action(args);

} catch(TheCheckedException e) {

// Handle exceptional condition

...

}

   

to this:

// Invocation with state-testing method and unchecked exception

if (obj.actionPermitted(args)) {

obj.action(args);

} else {

// Handle exceptional condition

...

}

   

If you suspect that the simple calling sequence will be the norm, then this API refactoring may be appropriate. The API resulting from this refactoring is essentially identical to the state-testing method API in and the same caveats apply: if an object is to be accessed concurrently without external synchronization or it is subject to externally induced state transitions, this refactoring is inappropriate, as the object's state may change between the invocations of actionPermitted and action . If a separate actionPermitted method would, of necessity, duplicate the work of the action method, the refactoring may be ruled out by performance concerns.

转载于:https://www.cnblogs.com/haokaibo/p/avoid-unnecessary-use-of-checked-exceptions.html

你可能感兴趣的文章
Java虚拟机规范(Java SE 7)笔记
查看>>
iOS - UIColor
查看>>
ARM(Cortex-M3)的中断向量
查看>>
应用层协议及ip地址划分
查看>>
C#中的委托和事件(续)
查看>>
阅读代码分析工具Understand 2.0试用
查看>>
一次失败的项目经理招聘经验
查看>>
怎么保存退出vi编辑
查看>>
项目优化之热更新
查看>>
执行带返回参数的存储过程
查看>>
ECNUOJ 2616 游黄山
查看>>
Linux 查询配置命令
查看>>
存储过程入门
查看>>
Java泛型的基本使用
查看>>
我的游戏学习日志8——数字游戏策划(3)数字游戏的概念
查看>>
智力逻辑题
查看>>
Phpcms V9导航循环下拉菜单的调用技巧
查看>>
SpringBoot前后端分离Instant时间戳自定义解析
查看>>
开发一个简单的 Vue 弹窗组件
查看>>
1076 Wifi密码 (15 分)
查看>>