gpt4 book ai didi

java - 如果另一个异常吃掉了它,我应该在顶部异常中保留对原始异常的引用吗?

转载 作者:行者123 更新时间:2023-12-01 18:31:04 25 4
gpt4 key购买 nike

考虑这个自定义Exception类:

public class CustomException extends Exception {

private static final long serialVersionUID = 1L;

public static final int EXCEPTION1 = 1;
public static final int EXCEPTION2 = 2;
public static final int EXCEPTION3 = 3;

private int exceptionType;
private Throwable guiltyException;

public CustomException(String message, int type, Throwable cause){
super(message);
this.exceptionType = type;
this.guiltyException = cause;
}

public int getExceptionType(){
return this.exceptionType;
}

public Throwable getGuiltyException(){
return this.guiltyException;
}

}

然后假设某个地方有这样的方法:

public SomeReturnType someMethod(SomeArgument argument) throws CustomException{
try{
someExceptionalMethodCall(); // Throws Exception1, Exception2, Exception3
} catch (Exception1 e1) {
throw new CustomException("Some info1", CustomException.EXCEPTION1, e1);
} catch (Exception2 e2) {
throw new CustomException("Some info2", CustomException.EXCEPTION2, e2);
} catch (Exception3 e3) {
throw new CustomException("Some info3", CustomException.EXCEPTION3, e3);
}
}

存储 Throwable 只是毫无意义的开销,我可以通过调整 CustomException< 的构造函数中对 Exceptionsuper 调用来避免?像这样:

public CustomException(String message, int type, Throwable cause){
super(message, cause);
this.exceptionType = type;
}

然后我就可以摆脱 guiltyExceptiongetGuiltyException

CustomException 类本身中存储 Throwable 原因有什么意义吗?

最佳答案

不,当 Throwable 已经具有该功能时,没有理由自己存储原因。您的类应该只引入额外信息,而不是已经有意义的重复字段。

除此之外,我期望能够调用getCause()并检索原始异常 - 而在您的原始代码中,我必须知道这是一个 CustomException,并调用 getGuiltyException()。这种情况的一个症状是,任何记录错误的通用代码都不会在您当前的版本中看到原因 - 而如果您使用异常链接的标准方法,则会看到原因。

关于java - 如果另一个异常吃掉了它,我应该在顶部异常中保留对原始异常的引用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24203658/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com