Error Handling

Related slides on offer

Figure 461. Compile- and runtime errors Slide presentation Create comment in forum
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 462. NullPointerException (NPE for short) Slide presentation Create comment in forum
final String s = null;
System.out.println(s.length());
Exception in thread "main" java.lang.NullPointerException
  at exceptionhandling.Npe.main(Npe.java:7)

Figure 463. NullPointerException is a class Slide presentation Create comment in forum

Figure 464. Throwing an exception Slide presentation Create comment in forum
...
if (somethingBadHappens) {
  throw new NullPointerException();
}
...

Note

Without countermeasures your program will terminate


Figure 465. Catching an exception by try {...} catch {...} Slide presentation Create comment in forum
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. 155

Mind your prey Create comment in forum

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 466. try {...} catch {...} syntax Slide presentation Create comment in forum
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]]
}]