IntroJB13.pdf
(
139 KB
)
Pobierz
Microsoft Word - CH13ExceptionHandling.DOC
Part IV: Developing Comprehensive Projects
This part of the book is devoted to several advanced
features of Java programming. The subjects treated include
the use of exception handling to make programs robust, the
use of internationalization support to develop projects for
international audiences, the use of multithreading to make
programs more responsive and interactive, the incorporation
of sound and images to make programs user-friendly, the use
of input and output to manage and process large quantities
of data, and the creation of client/server applications with
Java networking support. You will learn how to use these
features to develop comprehensive programs.
Chapter 13
Exception Handling
Chapter 14
Internationalization
Chapter 15
Multithreading
Chapter 16
Multimedia
Chapter 17
Input and Output
Chapter 18
Networking
Chapter 19
Java Data Structures
593
13
Exception Handling
Objectives
•
Understand the concept of exception handling.
•
Become familiar with exception types.
•
Claim exceptions in a method.
•
Throw exceptions in a method.
•
Use the try-catch block to handle exceptions.
•
Create your own exception classes.
•
Rethrow exceptions in a try-catch block.
•
Use the finally clause in a try-catch block.
•
Know when to use exceptions.
Introduction
Programming errors are unavoidable, even for experienced
programmers. In Chapter 2, "Primitive Data Types and
Operations," you learned that there are three categories of
errors: compilation errors, runtime errors, and logic
errors.
Compilation
errors
arise because the rules of the
language have not been followed. They are detected by the
compiler.
Runtime errors
occur while the program is running
if the environment detects an operation that is impossible
to carry out.
Logic errors
occur when a program doesn't
perform the way it was intended to. In general, syntax
errors are easy to find and easy to correct because the
compiler indicates where they came from and why they
occurred. You can use the debugging techniques introduced in
Chapter 2 to find logic errors. This chapter deals with
runtime errors.
Runtime errors cause
exceptions
: events that occur during
the execution of a program and disrupt the normal flow of
control. A program that does not provide the code to handle
exceptions may terminate abnormally, causing serious
problems. For example, if your program attempts to transfer
money from a savings account to a checking account but,
because of a runtime error, is terminated
after
the money is
594
drawn from the savings account and
before
the money is
deposited in the checking account, the customer will lose
money.
Java provides programmers with the capability to handle
runtime errors. With this capability, referred to as
exception handling
, you can develop robust programs for
mission-critical computing.
For example, the following program terminates abnormally,
because the divisor is 0, which causes a numerical error.
public class Test
{
public static void main(String[] args)
{
System.out.println(3/0);
}
}
You can handle this error in the following code using a new
construct called
the try-catch block
to enable the program
to catch the error and continue to execute.
public class Test
{
public static void main(String[] args)
{
try
{
System.out.println(3/0);
}
catch (Exception ex)
{
System.out.println("Error: " + ex.getMessage());
}
System.out.println("Execution continues");
}
}
This chapter introduces Java's exception-handling model. The
chapter covers exception types, claiming exceptions,
throwing exceptions, catching exceptions, creating exception
classes, rethrowing exceptions, and the finally clause.
Exceptions and Exception Types
Runtime errors occur for various reasons. For example, the
user may enter an invalid input, or the program may attempt
to open a file that doesn't exist, or the network connection
may hang up, or the program may attempt to access an out-of-
bounds array element. When a runtime error occurs, Java
raises an exception.
Exceptions are handled differently from the events of
graphics programming. (In Chapter 10, "Getting Started with
Graphics Programming," you learned the events used in
595
graphics.) An
event
may be ignored in graphics programming,
but an
exception
cannot be ignored. In graphics programming,
a listener must register with the source object. External
user action on the source object generates an event, and the
source object notifies the listener by invoking the handlers
implemented by the listener. If no listener is registered
with the source object, the event is ignored. However, when
an exception occurs, the program may terminate if no handler
can be used to deal with the exception.
A Java exception is an instance of a class derived from
Throwable. The Throwable class is contained in the java.lang
package, and subclasses of Throwable are contained in
various packages. Errors related to graphics are included in
the java.awt package; numeric exceptions are included in the
java.lang package because they are related to the
java.lang.Number class. You can create your own exception
classes by extending Throwable or a subclass of Throwable.
Figure 13.1 shows some of Java’s predefined exception
classes.
***Insert Figure 13.1 (Same as Figure 11.1 in the 3
rd
Edition,p480)
Figure 13.1
The exceptions are instances of the classes shown in this
diagram.
NOTE: The class names Error, Exception, and
RuntimeException are somewhat confusing. All the
classes are exceptions. Exception is just one of
these classes, and all the errors discussed here
occur at runtime.
The Error class describes internal system errors. Such
errors rarely occur. If one does, there is little you can do
beyond notifying the user and trying to terminate the
program gracefully. Examples of subclasses of Error are
LinkageError, VirtualMachineError, and AWTError. Subclasses
of LinkageError indicate that a class has some dependency on
another class, but that the latter class has changed
incompatibly after the compilation of the former class.
Subclasses of VirtualMachineError indicate that the Java
Virtual Machine is broken or has run out of the resources
necessary for it to continue operating. AWTError is caused
by a fatal error in the graphics programs.
The Exception class describes errors caused by your program
and external circumstances. These errors can be caught and
handled by your program. Exception has many subclasses.
596
Examples are ClassNotFoundException,
CloneNotSupportedException, IOException, RuntimeException,
and AWTException,
The ClassNotFoundException is raised if you attempt to use a
class that does not exist. It would occur, for example, if
you tried to run a nonexistent class using the
java
command.
The CloneNotSupportedException is raised if you attempt to
clone an object whose defining class does not implement the
Cloneable interface. Cloning objects were introduced in
Chapter 8, "Class Inheritance and Interfaces."
The RuntimeException class describes programming errors,
such as bad casting, accessing an out-of-bound array, and
numeric errors. Examples of subclasses of RuntimeException
are ArithmeticException, NullPointerException, and
IndexOutOfBoundsException.
ArithmeticException is for integer arithmetic. Java deals
with integer arithmetic differently from floating-point
arithmetic. Dividing by zero or modulus by zero is invalid
for integer arithmetic and throws ArithmeticException.
Floating-point arithmetic does not throw exceptions. For
floating-point arithmetic, dividing by zero overflows to
infinity See Appendix I, “Special Floating-Point Values,”
for a discussion on special values for floating-point
arithmetic.
The IOException class describes errors related to
input/output operations, such as invalid input, reading past
the end of a file, and opening a nonexistent file. Examples
of subclasses of IOException are InterruptedIOException,
EOFException, and FileNotFoundException.
The AWTException class describes exceptions in graphics
programming.
Understanding Exception Handling
Java's exception-handling model is based on three
operations:
claiming an exception
,
throwing an exception
,
and
catching an exception
, as shown in Figure 13.2.
***Insert Figure 13.2 (Same as Figure 11.2 in the 3
rd
Edition, p481)
Figure 13.2
The exception handling in Java consists of
claiming exception, throwing exception, and catching and
processing exceptions.
597
Plik z chomika:
rrdzony
Inne pliki z tego folderu:
bookcover.jpg
(9 KB)
index.html
(7 KB)
IntroJB01.pdf
(540 KB)
IntroJB06.pdf
(220 KB)
IntroJB10.pdf
(456 KB)
Inne foldery tego chomika:
3D Studio Max 4
61.ebooks
ABC Nagrywania Płyt CD
ABC Systemu Windows XP
Absolute Java 1st Edition
Zgłoś jeśli
naruszono regulamin