Java Lesson 12: Exceptions

2
30

Introduction

The Java language supports exception handling, an important feature for making robust programs. When a run-time error occurs it can throw an exception. Your program can catch the error and recover from the error condition or exit gracefully. The ability to handle adverse conditions makes your program more user-friendly.

Things That Go Wrong, Go Wrong, Go Wrong…

Sometimes errors occur while a program is running. A classic example is to attempt aAttempting to divide by zero is undefined. mathematical division operation where the denominator is equal to zero. This is a “divide by zero” error, because the mathematical result of dividing by zero is undefined. All computer languages will give some type of error message when this occurs, and often the program will crash or exit prematurely. Consider Program12a.java which attempts to divide 8 by 0.

Compile and execution of Program12a.java which results in an Arithmetic Exception.

Java reports the error as an ArithmeticException and notifies the user that the program attempted to divide by zero at line number 13 in the program. Unfortunately this is unhelpful to the end-user who may have used the program for a long time and has now lost a lot of work.

In Java, an exception handler let’s us intercept the error before the user sees it, and deal with the error in a controlled way.

Categories of Exceptions

Java has dozens of exceptions defined in the language, and many are rarely seen. Some of the most common are:

  1. ArithmeticException: An arithmetic error, such as divide-by-zero.
  2. NumberFormatException: An invalid conversion of a string to some other format, such as to an int or double.
  3. ArrayIndexOutOfBoundsException: An array index is out-of-bounds.

Handling Exceptions

General Information

To handle exceptions, you try the statements that might throw an exception, and then catch any objects thrown by the statements. Optionally, you can finally execute some other statements after catching the exception. The format is:

The statements in the try block executes and any exceptions generated are compared with the catch statement. If a match exists, then the statements in the catch block execute. If an exception does not occur, then the statements in the catch block do not execute (i.e., are skipped). You can have several catch statements to handle different exceptions which might occur. If you have any statements you need executed even if an exception is thrown, you can define a finally block. The code in the finally block will execute after the try block and/or the catch block has executed. Something to keep in mind is that the finally block doesn’t necessarily run immediately after the catch block – some other code in the program might run first. However, the statements in the finally block are guaranteed to run if an exception was caught. The finally block is generally used to clean things up, such as closing a file after it was read.

Handling ArithmeticException with try-catch

We can add exception handling to the previous program with try-catch statements. Program12b.java catches a divide by zero exception and displays a helpful error message to the user.

Compile and execution of Program12b.java which displays a user-friendly error message when a divide by zero occurs.

As shown in the screenshot above the program gracefully handles the divide by zero error condition with a more user-friendly error message and continues running instead of crashing.

The finally Statement

You can put a finally statement after a try-catch. Any code inside the finally block executes even if an exception is thrown. The finally block executes no matter what happens in the try block.

Program12c.java has a finally block which displays a message and sets the variable r to -1.

Compile and execution of Program12c.java which uses a try-catch-finally block when a divide by zero exception occurs.

Handling NumberFormatException with try-catch

Previously in Java tutorial Lesson 6: Simple Console Input / Output, we used the Scanner class to get input from the user as a text String and convert it to a number such as int or double. In that lesson we noted that problems occur if the user enters invalid values. For example, if the program expects a number and inadvertently receives characters, then Java raises an exception which causes the program to stop abruptly. Using what we learned about Conditionals and Exceptions we can enhance the programs in Lesson 6 to validate the user’s input and gracefully handle this possibility with more robust code.

Compile and execution of Program12d.java, which asks the user to enter an integer and handles invalid entry with try-catch.

Notice how the try-catch handles an invalid numeric entry. Use the code in Program12d.java in your programs when you ask the user to enter a number!

ArrayIndexOutOfBoundsException Handling with try-catch

Another common exception is when the programmer attempts to access an array index which is not within the bounds of the array, as in Program12e.java:

Compile and execution of Program12e.java, which attempts to access an array index out of bounds.

The safest way to avoid going beyond an array’s boundary is, as we learned in Java Lesson 9: Arrays, to use the length() method which returns the length of the array.

Other times you may need to use a try-catch statement to trap the ArrayIndexOutOfBoundsException.

Displaying the Java Stacktrace

If you want to display Java’s error message, also known as a stacktrace, when an exception occurs, then use the printStackTrace() method from the parent class of Exception to catch any possible exception. This is useful if you don’t know the name of the exception that Java will raise or if you want to see detailed error information for troubleshooting purposes.

Execution of Program12f.java with a Java StackTrace.

Define Your Own Exception and Throw It

You can throw your own objects, which are either subclasses of the Exception class, or any other object. To create your own exception, make a class that is a subclass of the Exception class. Here, we define a class called NumberTooBigException which is used if the user enters an integer greater than 999.

Then we can throw this exception in our program with a throw statement.

Program12f.java uses this concept to ask the user for an area code, which should be an integer less than or equal to 999. The program throws a programmer-defined exception if the number is too large, and it also catches any NumberFormatException exceptions as before.

Compile and execution of Program12f.java, which defines its own Exception class and throws an exception if the user enters an integer greater than 999.

More Than One Catch Statement

Notice that, as in the program above, a try statement can have more than one catch statement. You can, and should, try to catch any exception that could occur. This is more common when reading and writing data files (Input/Output operations) where any of several possible error conditions may occur, such as file not found, end of file, insufficient access permissions, etc.

Summary

In this lesson we learned how Java includes the concept of exception handling with the try, throw, catch, and finally statements. Exceptions are method calls made when the Java Virtual Machine (JVM) encounters a run-time error. As you write more programs you will find it beneficial to handle the error or exit gracefully.

Next Lesson

Exceptions can occur when performing Input/Output operations. Next we will move on to I/O Streams.

2 COMMENTS

  1. […] will demonstrate both ways in the examples below. Review Java Lesson 12: Exceptions if you need a […]

Leave a Reply