Java开发 - 异常 - 抛出异常

时间:2021-11-23 18:22:08

问题: 如何抛出一个系统异常并且捕获它

代码如下:

public class ThrowDemo {
static void demoproc() {
try {
throw new NullPointerException("demo");
} catch (NullPointerException e) {
System.out.println("Caught inside demoproc.");
throw e; // rethrow the exception
}
} public static void main(String args[]) {
try {
demoproc();
} catch (NullPointerException e) {
System.out.println("Recaught: " + e);
}
}
}

运行结果:

Caught inside demoproc.
Recaught: java.lang.NullPointerException: demo