在java中扩展异常/ RunTimeException? [英] Extending Exception/RunTimeException in java?

查看:592
本文介绍了在java中扩展异常/ RunTimeException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下类。

public class ValidationException extends RuntimeException {


}

public class ValidationException extends Exception {


}

我感到困惑的是,自定义异常应该如何扩展 RunTimeException ,当它必须扩展异常时。你可以解释一下,直接延续 RunTimeException 有什么缺点吗?

I am confused as to when the custom exception should extend RunTimeException and when it has to extend Exception. Could you please explain me is there any disadvantage of extending RunTimeException directly?

谢谢!

推荐答案


检查异常时调用RuntimeException(调用
代码必须处理它们)。

RuntimeException are unchecked while Exception are checked (calling code must handle them).

如果想要将其取消选中,则自定义异常应该扩展RuntimeException,否则使用异常扩展。

The custom exception should extends RuntimeException if you want to make it unchecked else extend it with Exception.

使用未经检查的异常,调用代码方法不需要在其throws子句中声明在执行方法期间可能抛出但未被捕获的RuntimeException的任何子类。

With unchecked exceptions calling code method is not required to declare in its throws clause any subclasses of RuntimeException that might be thrown during the execution of the method but not caught.

由于调用方法可能无法处理RuntimeException,所以在抛出RuntimeException 时需要注意

As the calling method may not handle RuntimeException, one needs to be careful while throwing RuntimeException.

运行时异常表示问题是编程问题的结果,因此,API客户端代码不能合理地为ex从他们那里恢复或以任何方式处理它们。这些问题包括算术异常,例如除以零;指针异常,例如尝试通过空引用访问对象;并索引异常,例如尝试通过太大或太小的索引访问数组元素。

Runtime exceptions represent problems that are the result of a programming problem, and as such, the API client code cannot reasonably be expected to recover from them or to handle them in any way. Such problems include arithmetic exceptions, such as dividing by zero; pointer exceptions, such as trying to access an object through a null reference; and indexing exceptions, such as attempting to access an array element through an index that is too large or too small.

运行时异常可以发生在程序中的任何位置,而在典型的,他们可以是非常多的。在每个方法声明中添加运行时异常都会减少程序的清晰度。因此,编译器不要求您捕获或指定运行时异常(尽管可以)。

Runtime exceptions can occur anywhere in a program, and in a typical one they can be very numerous. Having to add runtime exceptions in every method declaration would reduce a program's clarity. Thus, the compiler does not require that you catch or specify runtime exceptions (although you can).

源/进一步阅读: 未经检查的异常 - 争议

这篇关于在java中扩展异常/ RunTimeException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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