Java Reference
In-Depth Information
We can define our own exceptions by deriving a new class from
Exception
or
one of its descendants. The class we choose as the parent depends on what situa-
tion or condition the new exception represents.
The program in Listing 11.5 instantiates an exception object and
throws it. The exception is created from the
OutOfRangeException
class, which is shown in Listing 11.6. Note that this exception is not
part of the Java standard class library. It was created to represent the
situation in which a value is outside a particular valid range.
KEY CONCEPT
A new exception is defined by deriv-
ing a new class from the
Exception
class or one of its descendants.
LISTING 11.5
//********************************************************************
// CreatingExceptions.java Author: Lewis/Loftus
//
// Demonstrates the ability to define an exception via inheritance.
//********************************************************************
import
java.util.Scanner;
public class
CreatingExceptions
{
//-----------------------------------------------------------------
// Creates an exception object and possibly throws it.
//-----------------------------------------------------------------
public static void
main (String[] args)
throws
OutOfRangeException
{
final int
MIN = 25, MAX = 40;
Scanner scan =
new
Scanner (System.in);
OutOfRangeException problem =
new
OutOfRangeException ("Input value is out of range.");
System.out.print ("Enter an integer value between " + MIN +
" and " + MAX + ", inclusive: ");
int
value = scan.nextInt();
// Determine if the exception should be thrown
if
(value < MIN || value > MAX)
throw
problem;
System.out.println ("End of main method.");
// may never reach
}
}
Search WWH ::
Custom Search