Error Handling

Related slides on offer

Figure 498. Compile- and runtime errors Slide presentation
final int public  = 33;

final String s = null;
System.out.println(s.length()) ;

Compile time error: public is a Java keyword not to be used as variable's name.

Run time error: De-referencing null yields a NullPointerException.


Figure 499. NullPointerException (NPE for short) Slide presentation
final String s = null;
System.out.println(s.length());
Exception in thread "main" java.lang.NullPointerException
  at exceptionhandling.Npe.main(Npe.java:7)

Figure 500. NullPointerException is a class Slide presentation

Figure 501. Throwing an exception Slide presentation
...
if (somethingBadHappens) {
  throw new NullPointerException();
}
...

Note

Without countermeasures your program will terminate


Figure 502. Catching an exception by try {...} catch {...} Slide presentation
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 ...

exercise No. 175

Mind your prey

Q:

We reconsider:

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 ...");

What happens if NullPointerException is being replaced by OutOfMemoryError?

Is there a way to catch all possible exceptions?

A:

We have:

final String s = null;
try {
  System.out.println(s.length()) ;
} catch (final OutOfMemoryError e) {
  System.out.println("Dear user, something bad just happened");
}
System.out.println("Business as usual ...");

The runtime system throws a NullPointerException which is no subclass of OutOfMemoryError:

If NullPointerException was a subclass of OutOfMemoryError it would still be caught. But lacking an (upcast) inheritance relationship we are being left with the runtimes default terminating behaviour:

Exception in thread "main" java.lang.NullPointerException
  at exceptionhandling.NpeMsg.main(NpeMsg.java:8)
Figure 503. try {...} catch {...} syntax Slide presentation
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]]
}]