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 state开发者_开发知识库ment, without the throws clause, no error is there?? 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
Caught inside demoproc.
Recaught : java.lang.NullPointerException: demo
You only need throws
clause for checked Exceptions.
Observe these lines:
public static void main(String Args[]){
try[
The try
has a bracket, not a brace. Probably, you've been unsuccessfully compiling the program, and then re-running the old class file.
Because NullPoinerException
is a RuntimeException
. It doesn't need a throws
clause.
Unable to get what you meant be default handler. When the execption is thrown by
throw new NullPoinerException ("demo");
This is caught by the try catch block surrounding it.
Catch block in turn throws exception, which is caught by try catch block in main.
Hope this helps.
Edit after your comment: Also NullPoinerException exception is unchecked exception thus need not be mentioned as throws.
精彩评论