java - 为什么在 .NET 中不检查异常?

标签 java .net exception

我知道谷歌搜索可以找到合适的答案,但我更喜欢听听您的个人(也许是技术)意见。
Java和C#在抛出异常上的区别的主要原因是什么?
在 Java 中,抛出异常的方法的签名必须使用“throws”关键字,而在 C# 中,您在编译时不知道是否会抛出异常。

最佳答案

在文章The Trouble with Checked Exceptions在 Anders Hejlsberg(C# 语言的设计者)自己的声音中,C# 不支持在 Java 中发现和验证的检查异常有三个主要原因:

  • 对检查的异常中立

    “C# is basically silent on the checked exceptions issue. Once a better solution is known—and trust me we continue to think about it—we can go back and actually put something in place.”

  • 带有检查异常的版本控制

    “Adding a new exception to a throws clause in a new version breaks client code. It's like adding a method to an interface. After you publish an interface, it is for all practical purposes immutable, …”

    “It is funny how people think that the important thing about exceptions is handling them. That is not the important thing about exceptions. In a well-written application there's a ratio of ten to one, in my opinion, of try finally to try catch. Or in C#, using statements, which are like try finally.”

  • 检查异常的可扩展性

    “In the small, checked exceptions are very enticing…The trouble begins when you start building big systems where you're talking to four or five different subsystems. Each subsystem throws four to ten exceptions. Now, each time you walk up the ladder of aggregation, you have this exponential hierarchy below you of exceptions you have to deal with. You end up having to declare 40 exceptions that you might throw.… It just balloons out of control.”

在他的文章中,“Why doesn't C# have exception specifications? ”, Anson Horton (Visual C# Program Manager)还列出了以下原因(有关每个点的详细信息,请参阅文章):

  • 版本控制
  • 生产力和代码质量
  • 让类(class)作者区分是不切实际的 选中未选中异常
  • 难以确定接口(interface)的正确异常。

有趣的是,尽管如此,C# 确实支持给定方法通过 <exception> 抛出的异常的文档。标记和编译器甚至不厌其烦地验证引用的异常类型确实存在。但是,没有检查调用站点或方法的使用情况。

您可能还想查看 Exception Hunter ,这是 Red Gate Software 的商业工具,它使用静态分析来确定和报告方法抛出的异常,这些异常可能未被捕获:

Exception Hunter is a new analysis tool that finds and reports the set of possible exceptions your functions might throw – before you even ship. With it, you can locate unhandled exceptions easily and quickly, down to the line of code that is throwing the exceptions. Once you have the results, you can decide which exceptions need to be handled (with some exception handling code) before you release your application into the wild.

最后,Bruce Eckel , 作者 Thinking in Java ,有一篇文章叫做“Does Java need Checked Exceptions? ”,这可能也值得一读,因为为什么 C# 中不存在已检查异常的问题通常在与 Java 的比较中根深蒂固。

关于java - 为什么在 .NET 中不检查异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/124143/

相关文章:

java - 使用自定义用户对象时的 Spring session redis

c# - 使用 C# 在 RichTextBox 中突出显示语法

node.js - 如何使 Chai.js 的异常包含堆栈跟踪信息?

java - 仅在 java 的 Debug模式下抛出异常

java - 将我的依赖项放入我的 JAR 中

java - JUnit - 使用参数中的对象测试类实例化

c# - 从 Excel 单元格读取十进制值(在 C# 中)

.net - 错误: Cannot find the Style Property 'Template' on the type 'System.Windows.Controls.Primitives.Popup'

Java连接Get请求异常处理

java.lang.NoClassDefFoundError : net/sf/ehcache/concurrent/ReadWriteLockSync