[英]In Java, An exception thrown by us is not caught by the default handler? Right
But then in the following program, when the exception is re-thrown in the catch statement, without the throws clause, no error is there??但是接下来的程序中,当catch语句中重新抛出异常时,没有throws子句,就没有错误了?? How?
如何?
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);
}
}
}
THe output is output 是
Caught inside demoproc.
Recaught : java.lang.NullPointerException: demo
You only need throws
clause for checked Exceptions .对于已检查的 Exceptions ,您只需要
throws
子句。
Observe these lines:请注意以下几行:
public static void main(String Args[]){
try[
The try
has a bracket, not a brace. try
有一个括号,而不是大括号。 Probably, you've been unsuccessfully compiling the program, and then re-running the old class file.可能您一直未能成功编译程序,然后重新运行旧的 class 文件。
Because NullPoinerException
is a RuntimeException
.因为
NullPoinerException
是RuntimeException
。 It doesn't need a throws
clause.它不需要
throws
子句。
Unable to get what you meant be default handler.无法获得您的意思是默认处理程序。 When the execption is thrown by
当 execption 被抛出时
throw new NullPoinerException ("demo");
This is caught by the try catch block surrounding it.这被它周围的 try catch 块捕获。
Catch block in turn throws exception, which is caught by try catch block in main. Catch 块依次抛出异常,该异常被 main 中的 try catch 块捕获。
Hope this helps.希望这可以帮助。
Edit after your comment: Also NullPoinerException exception is unchecked exception thus need not be mentioned as throws.在您发表评论后进行编辑: NullPoinerException 异常也是未经检查的异常,因此无需提及为抛出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.