[英]Exception thrown is null
我有一个设置,例如...
public class MyClass {
Exception e = null;
try {
Game.runItNow();
} catch (Exception e) {
this.e = e;
}
if (this.e == null) {
showError();
}
}
public class Game {
public static void runItNow() throws IOException {
try {
HttpManager.getData()
} catch(IOException e) {
// here, e = null
throw e;
}
}
}
public class HttpManager {
public static String getData() throws IOException {
String someData = "The fox is brown";
String someWord = "fox";
if (someData.contains(someWord)) {
throw new IOException();
}
return someData;
}
}
问题是,当我捕获IO异常时e == null
。 不知道我是否在放屁,但是我很困惑。 为什么e == null
? 我正在抛出一个新的实例。
如果您上面的代码是实际的代码,那也就不足为奇了。 您的MyClass
。 您需要使用这些代码的静态块,主方法或构造函数。
如果您创建带有该代码的构造函数或main方法,则它将正常工作。
public class MyClass {
public static void main(String[] args) {
Exception e = null;
try {
Game.runItNow();
} catch (Exception e) {
this.e = e;
}
if (this.e == null) {
showError();
}
}
}
您将覆盖使用新IOException生成的IOException,而没有例外。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.