检查与未检查异常 [英] Checked vs Unchecked exception

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

问题描述

我研究过:然而,使用未经检查的异常,编译器不会强制客户端程序员捕获异常或在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块,
但我看到编译器力量将代码放在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.

我很困惑他们是什么?

推荐答案

未经检查的异常是扩展 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=)

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

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