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天全站免登陆