Handling Errors using Exceptions |
Your First Encounter with Java Exceptions briefly described what your first encounter with Java exceptions was probably like: it was likely in the form of an error message from the compiler complaining that you must either catch or declare exceptions. Then, Java's Catch or Declare Requirement discussed what exactly was meant by the error message and why the Java language designers decided to make this requirement. Now, we're going to show you both how to catch an exception and how to declare one.The Example
Both sections below, the one on catching an exception and the one on declaring an exception, use the same example. This example defines and implements a class named ListOfNumbers. The ListOfNumbers class calls two methods from classes in the Java packages that can throw exceptions. Catching and Handling Exceptions will show you how to write exception handlers for both exceptions, and Declaring the Exceptions Thrown by a Method will show you how to declare those exceptions instead of catching them.Catching and Handling Exceptions
Now that you've familiarized yourself with the ListOfNumbers class and where the exceptions can be thrown, let's write exception handlers to catch and handle those exceptions.This section covers the three components of an exception handler: the
try
,catch
, andfinally
blocks by showing you how to use them to write an exception handler for the ListOfNumbers class'swriteList()
method. In addition, this section contains a page that walks through thewriteList()
method and analyzes what occurs within the method during various scenarios.Declaring the Exceptions Thrown by a Method
If it is not appropriate for your method to catch and handle an exception thrown by a method that it calls, or if your method itself throws its own exception, you must declare in the method signature that the method throws the exception. Using the ListOfNumbers class this section shows you how to declare exceptions.
Handling Errors using Exceptions |