Java/C# 中的已检查异常是什么? [英] What are checked exceptions in Java/C#?

查看:24
本文介绍了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 不是 RuntimeExceptionError,或其中之一他们的子类.

In Java, checked exceptions are Throwables 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# 中的已检查异常是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆