3.4. Avoiding Exceptions¶
We will use the code example from the last section to demonstrate how we
might avoid the NullPointerException. You likely employed techniques like this in
your previous course.
Original Example
public class Exception {
public static void main(String[] args) {
exception();
} // main
public static void exception() {
String s = null;
if (s.length() > 1) {
System.out.println("string length > 1");
} // if
} // exception
} // Exception
To avoid the exception in the example above, you only need to ensure
that you do not invoke members (i.e., call instance methods or access
instance variables) using s when s is null. Here are ways
we might fix the problem:
if (s != null) {
if (s.length() > 1) {
System.out.println("string length > 1");
} // if
} // if
if ((s != null) && (s.length() > 1)) {
System.out.println("string length > 1");
} // if
In general, to avoid an exception, you need to understand the
conditions in which that exception object is thrown, then write code
that correctly identifies if those conditions are met prior to the
line of code that throws the exception object. Although it is
relatively easy to amend code to avoid NullPointerException
objects as they arise, the same statement cannot be said about
exception objects that are thrown in more complex scenarios. For
example, there may be a lot of conditions to check, including some
that are tricky to identify (the video in the next section will show
this type of scenario). Such exceptions are generally handled instead
of avoided, although there is no reason that a combination of both
handling and avoiding can’t be employed.
In the next section, you will see an example of handling exceptions instead of avoiding them.