向现有 NullPointerException 添加消息

问题描述 投票:0回答:4

我在我的方法中捕获了不同类型的异常。

如果异常是

NullPointerException
,我想向现有异常添加一条消息。

有没有办法向现有的 NullPointerException 添加消息?我不能只创建一个新的异常,因为我需要堆栈跟踪等。

我的想法是创建一个像这样的新异常:

new Exception("the message", myNullPointer);

但是,输出不是我需要的,因为这样,我的堆栈跟踪看起来像这样:

java.lang.Exception:
...bla
...bla

但我需要它来保持 NullPointerException 像这样:

java.lang.NullPointerException:
...bla
...bla

另外,重要的是我无法访问创建初始 NullPointer 的部分。所以我无法在开始时添加消息。

编辑:我知道我应该避免 NPE。但我必须对抛出的 NPE 施加影响。所以我必须做出反应。

java exception nullpointerexception throwable
4个回答
3
投票

正如评论中所指出的,这可能不是一个好主意,特别是因为空异常可能会在您没有预料到的情况下出现。

尽管如此,你可以像这样做你想做的事:

try {
    ...potentially throws exceptions...
} catch (Exception e) {
    RuntimeException re = new RuntimeException(e);
    re.setStackTrace(e.getStackTrace());
    throw re;
}

1
投票

我希望你正在看这个:

public class NPException extends RuntimeException{

    public NPException(String message, Throwable exception){
        super(message, exception);
    }

}

然后尝试:

throw new NPException("TEsting..", new NullPointerException().getCause());

会给你类似的东西:

线程“main”中的异常 NPException:TEsting.. 在 Test.main(Test.java:151) 在 sun.reflect.NativeMethodAccessorImpl.invoke0(本机方法)


0
投票

我很确定,按照您的建议在构造函数中传递原始异常是您能做的最好的事情。您也可以使用

.getCause()
来确定异常的原因。这样您就可以为自己构建更有意义的输出,例如手动记录。


0
投票

您需要调用 getCause() 来检索您的

NPE

String nullString = null;
try {
  nullString.split("/");
} catch (NullPointerException e) {
  Exception ex = new Exception("Encapsulated", e);

  System.out.println("Direct Stacktrace");
  ex.printStackTrace();

  System.out.println("With getCause");
  ex.getCause().printStackTrace();
}
© www.soinside.com 2019 - 2024. All rights reserved.