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# 中的检查异常是什么?
基础教程推荐
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 降序排序:Java Map 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01