java 为什么要抛出异常,好奇:为什么单独使用Java需要“抛出异常”语法?

这篇博客探讨了Java中强制方法声明可能抛出的已检查异常的原因,这一特性在Java社区中引起了激烈的辩论。文章引用了一些专家的观点,他们认为过度依赖已检查异常可能导致大型项目的问题。作者个人认为,检查异常在API设计中有其用途,特别是在封装底层异常为更适合抽象层的异常时。同时,博客还提到了C#语言选择不使用已检查异常的设计决策。
摘要由CSDN通过智能技术生成

正如其他答案所指出的那样,throws子句只需要

checked exceptions,这是目前只存在于Java中的一个功能.

关于Java为什么检查异常的官方答案是well documented:

Why did the designers decide to force

a method to specify all uncaught

checked exceptions that can be thrown

within its scope? Any Exception that

can be thrown by a method is part of

the method’s public programming

interface. Those who call a method

must know about the exceptions that a

method can throw so that they can

decide what to do about them. These

exceptions are as much a part of that

method’s programming interface as its

parameters and return value.

但是,即使在Java社区内,这个决定也是highly controversial:

Recently, several well-regarded

experts, including Bruce Eckel and Rod

Johnson, have publicly stated that

while they initially agreed completely

with the orthodox position on checked

exceptions, they’ve concluded that

exclusive use of checked exceptions is

not as good an idea as it appeared at

first, and that checked exceptions

have become a significant source of

problems for many large projects.

Eckel takes a more extreme view,

suggesting that all exceptions should

be unchecked; Johnson’s view is more

conservative, but still suggests that

the orthodox preference for checked

exceptions is excessive. (It’s worth

noting that the architects of C#, who

almost certainly had plenty of

experience using Java technology,

chose to omit checked exceptions from

the language design, making all

exceptions unchecked exceptions. They

did, however, leave room for an

implementation of checked exceptions

at a later time.)

就个人而言,我发现只有当你的API养成捕获所有异常的习惯并将它们作为适合你的抽象层的东西重新抛出时,才会发现检查异常是有用的.例如,碰巧使用磁盘或SQL后端来缓存数据的内存中对象缓存应该永远不会抛出IOException或SQLException – 相反,它应该抛出(并声明)一些用户定义的异常,如CacheFailureException或类似的异常.

此外,你可能会发现Ned Batchelder的文章Exceptions in the Rainforest对这个问题很有启发性.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值