
Java 435
It is sad when these errors occur. Really, it is. e error message prints out and the program sputters to a
halt, never to continue running again. Perhaps you have developed some techniques for protecting against
these error messages. For example:
if (index < somearray.length) {
somearray[index] = random(0,100);
}
e above is a form of “ error checking. ” e code uses a conditional to check that the index is valid
before an element at that index is accessed. e above code is quite conscientious and we should all aspire
to be so careful.
Not all situations are as simple to avoid, however, and this is where exception handling comes into play.
Exception handling refers to the process of handling exceptions , out of the ordinary events (i.e., errors)
that occur during the execution of a program.
e code structure for exception handling in Java is known as try catch . In other words, “ Try to run some
code. If you run into a problem, however, catch the error and run some other code. ” If an error is caught
using try catch, the program is allowed to continue. Let’s look at how we might rewrite the array index
error checking code try catch style.
try {
somearray[index] = 200;
} catch (Exception e) {
println( "Hey, that’s not a valid index! ");
}
e above code catches any possible exception that might occur. e type of error caught is the generic
Exception. However, if you want to execute certain code based on a specifi c exception, you can, as the
following code demonstrates.
try {
somearray[index] = 200;
} catch (ArrayIndexOutOfBoundsException e) {
println ( "Hey, that’s not a valid index! ");
} catch (NullPointerException e) {
println( "I think you forgot to create the array! ");
} catch (Exception e) {
println( "Hmmm, I dunno, something weird happened! ");
e.printStackTrace();
}
e above code, nevertheless, does nothing more than print out custom error messages. ere are
situations where we want more than just an explanation. For example, take the examples from Chapter 18
where we loaded data from a URL path. What if our sketch had failed to connect to the URL? It would
have crashed and quit. With exception handling, we can catch that error and fi ll the array with Strings
manually so that the sketch can continue running.
The code that might produce an error
goes within the “try” section. The
code that should happen if an error
occurs goes in the “catch” section.
Different “catch” sections
catch different types of
exceptions. In addition, each
exception is an object and
can therefore have methods
called on it. For example:
e.printStackTrace();
displays more detailed
information about the
exception.