已检查与未检查的异常

Checked vs Unchecked exception(已检查与未检查的异常)

本文介绍了已检查与未检查的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我研究过:但是,对于未经检查的异常,编译器不会强制客户端程序员捕获异常或在 throws 子句中声明它.事实上,客户端程序员甚至可能不知道异常可能会被抛出.例如,String 的 charAt() 方法抛出的 StringIndexOutOfBoundsException.

I've studied that: With an unchecked exception, however, the compiler doesn't force client programmers either to catch the exception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. eg, StringIndexOutOfBoundsException thrown by String's charAt() method.

什么意思?

根据该代码,无需在代码中放置 try catch 块,但我已经看到编译器强制将代码放入 try catch 块中.

according to that code there is no need to put try catch block in code, but i've seen compiler forces to put the code in try catch block.

我很困惑它们到底是什么?

I'm very confused what they are exactly?

推荐答案

未经检查的异常是那些扩展了 RuntimeException 类的异常.编译器永远不会强迫您捕获此类异常或强迫您在方法中使用 throws 关键字声明它.所有其他异常类型(不扩展 RuntimeException)都经过检查,因此必须声明为抛出和/或捕获.

Unchecked exceptions are those that extend RuntimeException class. Compiler will never force you to catch such exception or force you to declare it in the method using throws keyword. All other exception types (that do not extend RuntimeException) are checked and therefore must be declared to be thrown and/or catched.

当您希望方法的调用者(即 API 的用户)显式处理 API 中的异常情况时,可以使用已检查的异常.当您认为调用能够针对该异常情况做一些有意义的事情时,就会声明已检查的异常,例如重试调用、回滚更改或将其转换为一些用户可读的错误消息.

Checked exceptions are used when you want the caller of your method (i.e the user of your API) to explicitly handle the exceptional case in your API. Checked exceptions are declared when you believe the call will be able to do something meaningful with that exceptional case, like retrying the call, rolling changes back or converting it into some user-readable error message.

如果您认为调用对异常没有任何用处(尤其是当它表示错误或 API 的错误使用时),则应取消检查异常.此外,带有太多已检查异常的 API 可能会令人讨厌(例如,尝试使用 java 反射 API=)

If you believe that there is nothing useful the call can do about the exception (especially when it represents a bug, or a wrong usage of your API), then the exception should be unchecked. Also, an API with too many checked exceptions can be annoying to program with (e.g. try using java reflection API=)

这篇关于已检查与未检查的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:已检查与未检查的异常

基础教程推荐