What are checked exceptions in Java/C#?(Java/C# 中的检查异常是什么?)
问题描述
我是一名 C# 开发人员,偶尔使用 Java 进行编码.有人可以简单地解释一下 Java 中的检查异常是什么,为什么需要它?在 C# 中没有遇到过这个术语.
I am a C# developer doing occasional coding in Java. Can someone explain in simple terms what are checked exceptions in Java and why is it needed? Haven't come across this term in C#.
推荐答案
已检查异常是编译器要求您以某种方式处理的异常.
Checked exceptions are exceptions that the compiler require you handle in some way.
在 Java 中,检查的异常是 Throwable
不是 RuntimeException
、Error
或其中之一它们的子类.
In Java, checked exceptions are Throwable
s that are not RuntimeException
, Error
, or one of their subclasses.
Java 设计人员认为他们需要确保程序处理合理可能的异常.一个经典的例子是 IOException
.任何时候程序执行 I/O,都有可能失败.磁盘可能已满,文件可能不存在,可能存在权限问题等.
The Java designers felt they were needed to ensure programs handled exceptions that were reasonably likely. A classic example is IOException
. Any time a program does I/O, there is a possibility of failure. The disk could be full, the file might not exist, there might be a permissions problem, etc.
因此,Java 的设计使得程序必须以某种方式在语法上处理异常.这可能是一个 catch 块,或者以某种方式重新抛出异常.
Thus, Java is designed such that a program must syntactically handle the exception in some way. This could be with a catch block, or by rethrowing the exception in some way.
C# 没有检查异常.他们决定将这个问题留给应用程序开发人员(采访).检查异常是有争议的,因为它们会使代码变得冗长,而开发人员有时会用空的 catch 块来处理它们.此外,哪个标准库方法抛出检查异常可以是任意的.例如,为什么不 File.delete
(一个新的 Java 7 API 做这不同) throw IOException
?
C# does not have checked exceptions. They decided to leave this issue up to the application developers (interview). Checked exceptions are controversial because they can make code verbose, while developers sometimes handle them trivially with empty catch blocks. Further, it can be arbitrary which standard library methods throw checked exceptions. For instance, why doesn't File.delete
(a new Java 7 API does this differently) throw IOException
?
Hejlsberg 在采访中指出的另一个问题是版本可控制性.向 throw
子句添加检查异常会强制使用该方法的所有代码都被修改和重新编译.
Another concern Hejlsberg noted in that interview is versionability. Adding a checked exception to a throw
clause forces all code using that method to be modified and recompiled.
这篇关于Java/C# 中的检查异常是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java/C# 中的检查异常是什么?


- 如何使用WebFilter实现授权头检查 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01