Error Handling
Figure 513.
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)
... 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. 176
Mind your prey
Q: |
We reconsider:
What happens if Is there a way to catch all possible exceptions? |
A: |
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]]
}]