3.3. 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 need only ensure that you do not invoke members (i.e., call methods or access instance variables) using s when s is null. Here are ways we might fix the problem:

// use an if-statement to check
if (s != null) {
    if (s.length() > 1) {
        System.out.println("string length > 1");
    } // if
} // if
// avoid NullPointerException via short-circuiting
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. 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.

Test Yourself

Take a look at the code below. What do you expect will happen when you run it?

Once you have an answer, go ahead and compile and run the code Odin. Take a look at the output and make sure you understand what it is telling you. Then, modify the code to avoid the exception.

There are many ways to complete this task. Use this opportunity to play around - modify the code in various ways and see what happens!

public class CrashExample {
   public static void main(String[] args) {
      causeCrash();
   } // main

   public static void causeCrash() {
      String[] array = {"one", "two", "three"};

      System.out.println(array[3]);
   } // causeCrash
} // CrashExample