简体   繁体   English

如何编写链式异常Java类

[英]How to write Chained Exception Java classes

Specifically, which constructors should be overridden to qualify an exception as chainable ? 具体来说,应该重写哪些构造函数以将异常限定为可链接的

Throwable(Throwable cause) , Throwable(String message, Throwable cause) , or both? Throwable(Throwable cause)Throwable(String message, Throwable cause)还是两者兼而有之?

Resources: 资源:

http://docs.oracle.com/javase/8/docs/api/java/lang/Throwable.html https://docs.oracle.com/javase/tutorial/essential/exceptions/chained.html http://docs.oracle.com/javase/8/docs/api/java/lang/Throwable.html https://docs.oracle.com/javase/tutorial/essential/exceptions/chained.html


The following example shows how to use a chained exception.: 以下示例显示如何使用链式异常:

try {

} catch (IOException e) {
    throw new SampleException("Other IOException", e);
}

Unclear what you mean by "chainable" here. 不清楚这里所说的“可链接”是什么意思。

Given the links that you gave however, I'll assume that you mean that a Throwable has another Throwable as a cause. 鉴于您提供的链接,我将假设您的意思是Throwable具有另一个Throwable作为原因。

In this case you have no choice but to use the appropriate constructor; 在这种情况下,您别无选择,只能使用适当的构造函数。 for instance: 例如:

public class Root
    extends Exception
{
    public Root(final String msg, final Throwable cause)
    {
        super(msg, cause);
    }
}

Another, less known solution, but which exists since Java 7, is to "suppress" the exception. 另一个鲜为人知的解决方案,是自Java 7起存在的,它是“抑制”异常。 See this link . 看到这个链接

Which means that you should first define what you mean by "chained exceptions". 这意味着您应该首先定义“链式异常”的含义。 An exception, by its nature, is pretty much "final"; 从本质上讲,例外是“最终的”。 the need to embed exceptions into other exceptions is rare, but not unheard of (as to suppressed exceptions, see here for an example) 将异常嵌入其他异常的需求很少,但并非闻所未闻(关于抑制的异常,请参见此处的示例)

So, define your use case first and foremost! 因此,首先定义您的用例!

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

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