Вы находитесь на странице: 1из 11

Exception Handling

Introduction to Programming 1 1
Exception

An exception is a representation of an error
condition or a situation that is not the
expected result of a method.

Exceptions are built into the Java language
and are available to all program code.

Exceptions isolate the code that deals with
the error condition from regular program
logic.

Introduction to Programming 1 2
Exception handling

Is the technique of catching the exceptions that
might be thrown during runtime.


FORMAT

try {
…. body-code
} catch (exception-classname variable-name) {
….handler-code
}

Introduction to Programming 1 3
The try/catch statement has
four parts

The body-code contains code that might throw the
exception that we want to handle.

The exception-classname is the class name of the
exception we want to handle.

The variable-name specifies a name for a variable
that will hold the exception object if the exception
occurs.

The handler-code contains the code to execute if
the exception occurs.

Introduction to Programming 1 4
Common Exceptions

ArithmeticException--thrown if a program attempts
to perform division by zero

ArrayIndexOutOfBoundsException--thrown if a
program attempts to access an index of an array
that does not exist

StringIndexOutOfBoundsException--thrown if a
program attempts to access a character at a non-
existent index in a String

NullPointerException--thrown if the JVM attempts to
perform an operation on an Object that points to no
data, or null
Introduction to Programming 1 5
Common Exceptions

NumberFormatException--thrown if a program is
attempting to convert a string to a numerical
datatype, and the string contains inappropriate
characters (i.e. 'z' or 'Q')

ClassNotFoundException--thrown if a program can
not find a class it depends at runtime (i.e., the
class's ".class" file cannot be found or was removed
from the CLASSPATH)

IOException--actually contained in java.io, but it is
thrown if the JVM failed to open an I/O stream

Introduction to Programming 1 6
Example1

Introduction to Programming 1 7
Example2

Introduction to Programming 1 8
Example3

Introduction to Programming 1 9
Example4

Introduction to Programming 1 10
Example5

Introduction to Programming 1 11

Вам также может понравиться