简体   繁体   English

为什么选择Java Runtime - unChecked异常需要子类

[英]Why Java Runtime - unChecked exception needs to sub class

Java Runtime Exception is used to check un-checked exception. Java Runtime Exception用于检查未检查的异常。 It is accepted standard that to sub class JavaRunTimeException. 它是子类JavaRunTimeException的公认标准。 Can you please explain me the reason behind sub classing without directly using it as below. 你可以解释一下子类的背后原因而不直接使用它,如下所示。

try {
    int x = Integer.parseInt(args[0])/Integer.parseInt(args[0]);
} catch (RuntimeException e) {

}

Recommended approach 推荐的方法

public class ServiceFaultException extends RuntimeException {}

try {
    int x = Integer.parseInt(args[0])/Integer.parseInt(args[0]);
} catch (ServiceFaultException e) {

}

I would like to know reasons for this recommendation. 我想知道这项建议的原因。 ?

Exceptions are used to give some meaning to an error that is not handled right away where it occurs. 异常用于为错误提供一些意义,错误不会立即处理。 Subclassing RuntimeException allows you to give more meaning and differentiate between several RuntimeExceptions . 子类RuntimeException允许您提供更多含义并区分几个RuntimeExceptions

For instance, it is useful to be able to tell the difference between IllegalArgumentException and NumberFormatException , which are both RuntimeException s. 例如,能够告诉IllegalArgumentExceptionNumberFormatException之间的区别很有用,它们都是RuntimeException

EDIT: As @Dyrborg said, catching RuntimeException can also be dangerous because anything could throw it without your knowledge. 编辑:正如@Dyrborg所说,捕获RuntimeException也可能是危险的,因为任何事情都可能在你不知情的情况下抛出它。 Better handle only what you control. 更好地处理您控制的内容。

ASIDE: You could tell me "why not a checked Exception then ?". ASIDE:您可以告诉我“为什么不检查Exception呢?”。 I usually use RuntimeException s when it corresponds to an incorrect use of a method (illegal argument for instance). 我通常使用RuntimeException因为它对应于方法的错误使用(例如非法参数)。 It means something the programmer can ensure to avoid. 这意味着程序员可以确保避免的事情。 When it comes to user input, or internet connection, which is not reliable, then Exception s are more appropriate, because the programmer must handle these error cases. 当涉及用户输入或互联网连接时,这是不可靠的,那么Exception更合适,因为程序员必须处理这些错误情况。

Can you please explain me the reason behind sub classing without directly using it as below. 你可以解释一下子类的背后原因而不直接使用它,如下所示。

The same reason as applies to subclassing any other exception. 同样的原因适用于继承任何其他异常。 The language provides the facility to catch specific subclasses, so why wouldn't you use it? 该语言提供了捕获特定子类的工具,那么为什么不使用它呢?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM