Exception Handling in Java
Exception handling in Java provides a simple straightforward technology to process unexpected behavior in code. This tutorial introduces the basics of how it's done.
An exception causes your program to deviate from the 'normal' or expected logic flow and go off to do something else. We usually think of exceptions as those events that take place when something goes wrong. That's not always the case, but the mechanics are the same regardless of why the exception occurs.
Example: code with no exception handling
Figure 01 depicts a code snippet that will cause an exception (line 12). Even though the code builds properly, at run time it will 'crash' because it's not possible to divide an integer by zero.
Figure 02 illustrates the output of the program in Figure 01. The exception was thrown in Line 12. Since the program isn't set up to handle the exception, Java takes over. When Java takes over, the programmer loses control.
As a developer, I much prefer to handle my own execptions rather than dumping the user back to the O/S.
Figure 03 contains our example program with modifications to handle the exception. We have implemented the try/catch block. Any exception that is thrown from the try block will cause execution to transfer into the catch block. The code in the catch block is at the discretion of the programmer; it can actually be left blank.
In our example the catch block contains logic to print a user-friendly message that contains useful information about what went wrong.
Figure 04 contains the output of our modified program. Instead of allowing Java to take over and process the exception, execution passes into the catch block. The programmer keeps control of the program.
After the catch block executes, the program continues executing the code immediately below the try/catch syntax. In Figure 05 we added code to the program in that location.
Exceptions aren't just for handling error conditions, Throwing a programmatic exception can be a useful strategy for exiting from a set of nested loops or other complex logic. In our next tutorial we will look at how to do that.