Exception Handling in
Java
Exception Handling in Java 1
Introduction
Users have high expectations for the code
we produce.
Users will use our programs in unexpected
ways.
Due to design errors or coding errors, our
programs may fail in unexpected ways
during execution
Exception Handling in Java 2
Introduction
It is our responsibility to produce quality
code that does not fail unexpectedly.
Consequently, we must design error
handling into our programs.
Exception Handling in Java 3
Exception Handling
• Java has a predefined set of exceptions and errors that can occur during
execution
• A program can deal with an exception in one of three ways:
ignore it
handle it where it occurs
handle it an another place in the program
• The manner in which an exception is processed is an important design
consideration
10-4
Errors and Error Handling
An Error is any unexpected result obtained from a
program during execution.
Unhandled errors may manifest themselves as
incorrect results or behavior, or as abnormal
program termination.
Errors should be handled by the programmer, to
prevent them from reaching the user.
Exception Handling in Java 5
Errors and Error Handling
Some typical causes of errors:
Memory errors (i.e. memory incorrectly allocated, memory leaks, “null
pointer”)
File system errors (i.e. disk is full, disk has been removed)
Network errors (i.e. network is down, URL does not exist)
Calculation errors (i.e. divide by 0)
Exception Handling in Java 6
Errors and Error Handling
More typical causes of errors:
Array errors (i.e. accessing element –1)
Conversion errors (i.e. convert ‘q’ to a number)
Exception Handling in Java 7
Errors and Error Handling
Traditional Error Handling
1. Every method returns a value (flag) indicating either
success, failure, or some error condition. The calling
method checks the return flag and takes appropriate
action.
Downside: programmer must remember to always check
the return value and take appropriate action. This
requires much code (methods are harder to read) and
something may get overlooked.
Exception Handling in Java 8
Errors and Error Handling
Traditional Error Handling
Where used: traditional programming languages (i.e. C) use this method for
almost all library functions (i.e. fopen() returns a valid file or else null)
Exception Handling in Java 9
Errors and Error Handling
Traditional Error Handling
2. Create a global error handling routine, and use some
form of “jump” instruction to call this routine when an
error occurs.
Downside: “jump” instruction (GoTo) are considered
“bad programming practice” and are discouraged. Once
you jump to the error routine, you cannot return to the
point of origin and so must (probably) exit the program.
Exception Handling in Java 10
Errors and Error Handling
Traditional Error Handling
Where used: many older programming texts (C, FORTRAN) recommended
this method to programmers. Those who use this method will frequently
adapt it to new languages (C++, Java).
Exception Handling in Java 11
Errors and Error Handling
Exceptions – a better error handling
Exceptions are a mechanism that provides the best of
both worlds.
Exceptions act similar to method return flags in that any
method may raise and exception should it encounter an
error.
Exceptions act like global error methods in that the
exception mechanism is built into Java; exceptions are
handled at many levels in a program, locally and/or
globally.
Exception Handling in Java 12
Exceptions
What are they?
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.
Exception Handling in Java 13
Exceptions
How are they used?
Exceptions fall into two categories:
Checked Exceptions
Unchecked Exceptions
Checked exceptions are inherited from the core Java
class Exception. They represent exceptions that are
frequently considered “non fatal” to program execution
Checked exceptions must be handled in your code, or
passed to parent classes for handling.
Exception Handling in Java 14
Exceptions
How are they used?
Unchecked exceptions represent error conditions that are considered
“fatal” to program execution.
You do not have to do anything with an unchecked exception. Your
program will terminate with an appropriate error message.
June 14, 2001 Exception Handling in Java 15
Exceptions
Examples:
Checked exceptions include errors such as “array index out of bounds”, “file
not found” and “number format conversion”.
Unchecked exceptions include errors such as “null pointer”.
Exception Handling in Java 16
Exceptions
How do you handle exceptions?
Exception handling is accomplished through the “try – catch” mechanism,
or by a “throws” clause in the method declaration.
For any code that throws a checked exception, you can decide to handle the
exception yourself, or pass the exception “up the chain” (to a parent class).
Exception Handling in Java 17
Exceptions
How do you handle exceptions?
To handle the exception, you write a “try-catch” block.
To pass the exception “up the chain”, you declare a
throws clause in your method or class declaration.
If the method contains code that may cause a checked
exception, you MUST handle the exception OR pass the
exception to the parent class (remember, every class has
Object as the ultimate parent)
Exception Handling in Java 18
Coding Exceptions
Try-Catch Mechanism
Wherever your code may trigger an exception, the normal code logic is
placed inside a block of code starting with the “try” keyword:
After the try block, the code to handle the exception should it arise is
placed in a block of code starting with the “catch” keyword.
Exception Handling in Java 19
Coding Exceptions
Try-Catch Mechanism
You may also write an optional “finally” block. This block contains code that
is ALWAYS executed, either after the “try” block code, or after the “catch”
block code.
Finally blocks can be used for operations that must happen no matter what
(i.e. cleanup operations such as closing a file)
Exception Handling in Java 20
Coding Exceptions
Example
try {
… normal program code
}
catch(Exception e) {
… exception handling code
}
Exception Handling in Java 21
Coding Exceptions
Passing the exception
In any method that might throw an exception, you may declare the method
as “throws” that exception, and thus avoid handling the exception yourself
Example
public void myMethod throws IOException {
… normal code with some I/O
}
Exception Handling in Java 22
Coding Exceptions
Types of Exceptions
All checked exceptions have class “Exception” as the parent class.
You can use the actual exception class or the parent class when referring to
an exception
Exception Handling in Java 23
Coding Exceptions
Types of Exceptions
Examples:
public void myMethod throws Exception {
public void myMethod throws IOException {
try { … }
catch (Exception e) { … }
try { … }
catch (IOException ioe) { … }
Exception Handling in Java 24
The finally Clause
• A try statement can have an optional clause following the catch clauses,
designated by the reserved word finally
• The statements in the finally clause always are executed
• If no exception is generated, the statements in the finally clause are
executed after the statements in the try block complete
• If an exception is generated, the statements in the finally clause are
executed after the statements in the appropriate catch clause complete
10-25
Code Examples
1. Demonstration of an unchecked exception (NullPointerException)
2. Demonstration of checked exceptions:
Passing a DivideByZeroException
Handling a DivideByZeroException
June 14, 2001 Exception Handling in Java 26
Summary
Exceptions are a powerful error handling mechanism.
Exceptions in Java are built into the language.
Exceptions can be handled by the programmer (try-catch), or handled by
the Java environment (throws).
Exception Handling in Java 27
The Exception Class
Hierarchy - Summary
• Classes that define exceptions are related by inheritance, forming an
exception class hierarchy
• All error and exception classes are descendents of the Throwable
class
• A programmer can define an exception by extending the Exception
class or one of its descendants
• The parent class used depends on how the new exception will be used
10-28
Checked Exceptions - Summary
• An exception is either checked or unchecked
• A checked exception either must be caught by a method, or must be
listed in the throws clause of any method that may throw or propagate
it
• A throws clause is appended to the method header
• The compiler will issue an error if a checked exception is not caught or
asserted in a throws clause
10-29
Unchecked Exceptions- Summary
• An unchecked exception does not require explicit handling, though it
could be processed that way
• The only unchecked exceptions in Java are objects of type
RuntimeException or any of its descendants
• Errors are similar to RuntimeException and its descendants in that:
Errors should not be caught
Errors do not require a throws clause
10-30
I/O Exceptions
• A stream is a sequence of bytes that flow from a source to a destination
• In a program, we read information from an input stream and write
information to an output stream
• A program can manage multiple streams simultaneously
10-31
Standard I/O
• There are three standard I/O streams:
standard output – defined by System.out
standard input – defined by System.in
standard error – defined by System.err
• We use System.out when we execute println statements
• System.out and System.err typically represent a particular
window on the monitor screen
• System.in typically represents keyboard input, which we've used
many times with Scanner objects
10-32
The IOException Class
• Operations performed by some I/O classes may throw an
IOException
A file might not exist
Even if the file exists, a program may not be able to find it
The file might not contain the kind of data we expect
• An IOException is a checked exception
10-33
Writing Text Files
• The FileWriter class represents a text output file, but with minimal
support for manipulating data
• Therefore, we also rely on PrintStream objects, which have print
and println methods defined for them
10-34