问题描述
|
但是然后在以下程序中,当catch语句中重新引发异常且没有throws子句时,就没有错误了?
怎么样?
Class Throwdemo {
static void demoproc(){
try{
throw new NullPoinerException (\"demo\");
}catch(NullPointerException e) {
System.out.println(\"Caught inside demoproc.\");
throw e;
}
}
public static void main(String Args[]){
try[
demoproc();
}catch(NullPointerException e) {
System.out.println(\"Recaught : \" + e);
}
}
}
输出是
Caught inside demoproc.
Recaught : java.lang.NullPointerException: demo
解决方法
您只需要
throws
子句即可查看已检查的异常。
, 注意以下几行:
public static void main(String Args[]){
try[
try
有括号,而不是花括号。可能是您未能成功编译程序,然后重新运行旧的类文件。
, 因为NullPoinerException
是RuntimeException
。它不需要throws
子句。
, 无法获得您的意思是默认处理程序。当执行被抛出时
throw new NullPoinerException (\"demo\");
这由周围的try catch块捕获。
捕获块依次引发异常,该异常由main中的try捕获块捕获。
希望这可以帮助。
在评论后进行编辑:另外,NullPoinerException异常是未经检查的异常,因此无需在抛出时提及。