Exception" syntax required in Java alone?-6ren"> Exception" syntax required in Java alone?-我们都知道它是必需的。 但是为什么仅在 Java 中需要它,而其他具有异常处理能力的类似语言不需要我们编写“throws Exception”?有没有人知道在设计 Java 语言时发生了什么以及为什么-6ren">
gpt4 book ai didi

java - 好奇 : Why is the "throws Exception" syntax required in Java alone?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:31:26 34 4
gpt4 key购买 nike

我们都知道它是必需的。

但是为什么仅在 Java 中需要它,而其他具有异常处理能力的类似语言不需要我们编写“throws Exception”?有没有人知道在设计 Java 语言时发生了什么以及为什么要这样做?只是好奇。

附言这可能不是一个实际或真正必要的问题 - 它可能对我正在进行的项目无论如何都没有帮助。但是某些语言特性激起了我的好奇心 :D

编辑看来我的问题很含糊!我想我错误地表达了这个问题。在处理 Java 代码的编程过程中,我们需要在某些时候使用“throws Exception”类语法。但是在 C# 或 C++ 甚至 VB.Net 和 PHP 中从来不需要类似的东西。那么为什么只有 Java 坚持这样做呢?

最佳答案

正如这里的其他答案所指出的,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.

但是,这个决定是highly controversial ,甚至在 Java 社区内:

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 后端来缓存数据的内存中对象缓存不应该抛出 IOExceptionSQLException —— 相反,它应该抛出(和声明)一些用户定义的异常,如 CacheFailureException 或类似的。

此外,您还可以找到 Ned Batchelder 的文章 Exceptions in the Rainforest对这个问题很有启发性。

关于java - 好奇 : Why is the "throws <SomeSpecific>Exception" syntax required in Java alone?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3702420/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com