Start of Tutorial > Start of Trail > Start of Lesson | Search |
Your First Encounter with Java Exceptions briefly described how you were (probably) first introduced to Java exceptions: a compiler error complaining that you must either catch or specify exceptions. Then, Java's Catch or Specify Requirement discussed what exactly the error message means and why the Java language designers decided to make this requirement. We're now going to show you both how to catch an exception and how to specify one.
ListOfNumbers
ExampleThe sections below, both the one on catching an exception and the one on specifying an exception, use the same example. This example defines and implements a class namedListOfNumbers
. TheListOfNumbers
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 Specifying the Exceptions Thrown by a Method will show you how to specify those exceptions instead of catching them.
Once you've familiarized yourself with theListOfNumbers
class and where the exceptions can be thrown, you can learn how to 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 theListOfNumbers
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.
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 specify in the method signature that the method
throws the exception.
Using the ListOfNumbers
class, this section shows you how to specify exceptions
that a method throws.
Start of Tutorial > Start of Trail > Start of Lesson | Search |