Error Handling
NullPointerException
(NPE for short) final String s = null;
System.out.println(s.length());
Exception in thread "main" java.lang.NullPointerException at exceptionhandling.Npe.main(Npe.java:7)
NullPointerException
is a class ...
if (somethingBadHappens) {
throw new NullPointerException();
}
...
Note
Without countermeasures your program will terminate
final String s = null;
try {
System.out.println(s.length()) ;
} catch (final NullPointerException e) {
System.out.println("Dear user, something bad just happened");
}
System.out.println("Business as usual ...");
Dear user, something bad just happened Business as usual ...
No. 170
Mind your prey
Q: |
We reconsider:
What happens if Is there a way to catch all possible exceptions? |
A: |
We have:
The runtime system throws a If Exception in thread "main" java.lang.NullPointerException at exceptionhandling.NpeMsg.main(NpeMsg.java:8) |
try {
[code that may throw an exception]
}[catch (ExceptionType-1 e) {
[code that is executed when ExceptionType-1 is thrown]
}] [catch (ExceptionType-2 e) {
[code that is executed when ExceptionType-2 is thrown]
}]
...
} [catch (ExceptionType-n e) {
[code that is executed when ExceptionType-n is thrown]
}]
[finally {
[code that runs regardless of whether an exception was thrown]]
}]