Java Exceptions  «Prev  Next»

Lesson 1

Introduction to Java Exceptions

This module discusses a key part of the Java language and libraries known as exceptions. Exceptions are Java's way of reporting and working with errors. They allow programmers to explicitly and formally define a control flow for errors, and they separate error detection from error handling.
By the end of the module, you should be able to:
  1. Describe why exceptions occur
  2. Catch exceptions
  3. Throw exceptions
  4. Make your own exceptions
  5. Be able to use the finally keyword

The term "exception" means exceptional condition and is an occurrence that alters the normal program flow. Many factors can lead to exceptions, including
  1. hardware failures,
  2. resource exhaustion, and
  3. improper coding.
When an exceptional event occurs in Java, an exception is said to be "thrown." The code that is responsible for doing something about the exception is called an "exception handler," and it "catches" the thrown exception.
Exception handling works by transferring the execution of a program to an appropriate exception handler when an exception occurs.
For example, if you call a method that opens a file but the file cannot be opened, execution of that method will stop, and the code that you wrote to deal with this situation will be run. Therefore, we need a way to tell the JVM what code to execute when a certain exception happens.
To do this, we use the try and catch keywords. The try is used to define a block of code in which exceptions may occur. This block of code is called a guarded region (which really means "risky code goes here"). One or more catch clauses match a specific exception (or group of exceptions) to a block of code that handles it.

In figure 2.1, do you think the code in bold in the classes ArrayAccess, OpenFile, and MethodAccess have anything in common?
Figure 2.1 ArrayAccess, OpenFile, and MethodAccess
Given the title of this module, this question was easy to answer. Each of these three statements is associated with throwing an exception or an error.