[英]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.