gpt4 book ai didi

Java 自定义异常抛出在不同项目之间的行为不同

转载 作者:行者123 更新时间:2023-12-02 08:33:02 25 4
gpt4 key购买 nike

我试图在我的代码中调用以下内容:

 public void checkParticleLightRestriction(Particle parent) throws LightException {
if ( parent == null ) {
throw new LightException("quantum-particle-restrict.23", this);
}

在一个项目中,抛出异常,其效果类似于调用“return”,即我立即返回到调用此方法的点。

但是,在另一个项目中,我被从当前包中抛出,并抛出到此方法之前的某个点。

我不是被赶出酒吧,而是被一路驱逐出境。

我的选择是将 throw 包装在 try/catch 中,但我想知道为什么这两个项目之间的行为存在差异?

2009 年 5 月 9 日我一直在考虑你的建议,但我仍然没有解决这个问题。无论 Exception 类是扩展 RuntimeException 还是只是 Exception,在该特定项目中似乎都不会调用抛出自定义异常的调用。

public class LightException extends Exception {

...etc

public LightException(String errorCode, Object object) {

super(errorCode == null ? null : errorStrings.getString(errorCode));
this.errorCode = errorCode;
this.invalidObject = object;
}

public LightException(String errorCode, Object object, Exception exception) {
this(errorCode, object);
add(exception);
}

...
}

任何想法表示赞赏。

最佳答案

如果不查看调用此方法的代码,就不可能知道发生了什么。

也许在一个项目中,异常被捕获,而在另一个项目中没有?如果 LightException 是未经检查的异常,则可能会发生这种情况。

编辑:

您(在原来的问题中)说:

the exception is thrown and ... returned back to the point immediately succeeding where this method was called.

唯一可能发生这种情况的情况是,当调用 checkParticleLightRestriction() 的方法被包装在 try...catch block 中时,例如:

try {
checkParticleLightRestriction(particle);
} catch (LightException e) {
// do something with e
}

// this is the point 'immediately succeeding where this method was called'

关于Java 自定义异常抛出在不同项目之间的行为不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2778386/

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