不知何故,我今天遇到了一个错误,我正在尝试复制它。
我相信下面的代码会抛出 NullPointerException 因为 ep
未实例化,但我无法模拟它..
我相信实例变量ep
当从 main 抛出异常时为 null。但运行它不会显示 NullPointerException。
当抛出异常( throw e.getILException(100)
)时,是 MyException.MyException()
调用了构造函数?
package sg.java.testException;
public class MyException extends Exception {
Exception ep;
public MyException() {
super();
ep = new Exception();
}
public OtherException getILException(long txnId) {
// the error is here, according to the stacktrace
return new OtherException(ep, ep.toString());
}
}
来电者:
public static void main(String args[]) throws OtherException{
try{
Car.run();
}catch (MyException e){
throw e.getILException(100);
}
}
汽车代码:
public class Car {
public static void run() throws MyException {
throw new MyException();
}
}
我希望能够复制此异常:
java.lang.NullPointerException
at sg.java.testException.MyException.getILException(MyException.java:13)
at sg.java.testException.ExceptionTest.main(ExceptionTest.java:8)
谢谢!
最佳答案
When the exception is thrown (throw e.getILException(100)), is the MyException.MyException() constructor called?
没有。在此之前被调用。语句 throw e.getILException(100)
调用方法 getILException(...)
,然后抛出
从该方法返回的任何内容。
我在 MyException
的构造函数中注释掉了 ep = new Exception();
行。
class OtherException extends Exception {
OtherException(Exception ex, String exStr) {}
}
class MyException extends Exception {
Exception ep;
public MyException() {
super();
// ep = new Exception();
}
public OtherException getILException(long txnId) {
// the error is here, according to the stacktrace
return new OtherException(ep, ep.toString());
}
}
public class Test {
public static void main(String args[]) throws OtherException {
try{
throw new MyException();
}catch (MyException e){
throw e.getILException(100);
}
}
}
结果如下。
Exception in thread "main" java.lang.NullPointerException
at MyException.getILException(Test.java:16)
at Test.main(Test.java:25)
关于自定义异常中的Java异常NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8162735/