【发布时间】:2016-06-22 08:19:46
【问题描述】:
我正在研究 try-catch 块。 这里我们通过 blowup() 抛出 NullPointerException , 甚至我们可以赋值
Exception e = new NullPointerException();
BlewIt 类又是一个类型 Exception 类。 所以我们抛出的异常必须在 catch 块中被捕获,但它没有。
class BlewIt extends Exception {
BlewIt() { }
BlewIt(String s) { super(s); }
}
class Test {
static void blowUp() throws BlewIt {
throw new NullPointerException();
}
public static void main(String[] args) {
try {
blowUp();
} catch (BlewIt b) {
System.out.println("Caught BlewIt");
} finally {
System.out.println("Uncaught Exception");
}
}
}
输出:
Uncaught Exception
Exception in thread "main" java.lang.NullPointerException
at Test.blowUp(Test.java:7)
at Test.main(Test.java:11)
但是如果你写这样的代码,它工作正常:
try {
blowUp();
} catch (Exception b) {
System.out.println("Caught BlewIt");
} finally {
System.out.println("Uncaught Exception");
}
现在 BlewIt 是 NullPointerException 类型,但我仍然得到相同的输出。
class BlewIt extends NullPointerException {
BlewIt() {
}
BlewIt(String s) {
super(s);
}
}
class Test {
static void blowUp() throws BlewIt {
throw new NullPointerException();
}
public static void main(String[] args) {
Exception e = new NullPointerException();
try {
blowUp();
} catch (BlewIt b) {
System.out.println("Caught BlewIt");
} finally {
System.out.println("Uncaught Exception");
}
}
}
请帮我弄清楚它背后的概念。
【问题讨论】:
-
仅仅因为
BlewIt是Exception并不意味着NullPointerException是BlewIt类型——它不是。 -
@TobiasBrösamle 感谢您的快速回复。明白你的意思。并尝试了一些不同的东西并添加了更多代码。
-
@TobiasBrösamle 虽然 BlewIt 现在是 NullPointerException 类型,但我仍然得到相同的输出。
-
是的,因为我正在抛出一个超类,而不是子类....对吗?
-
对。在您的最新示例中,
BlewIt是NullPointerException- 但NullPointerException不是BlewIt。这就是为什么它仍然不起作用。您需要抛出BlewIt才能使其工作,而不是超类,
标签: java exception nullpointerexception try-catch try-catch-finally