Java Reference
In-Depth Information
Chapter 9
Exception Handling
In this chapter, you will learn
•
About error handling in Java using exceptions
try-catch
blocks to handle exceptions
•
How to use
finally
blocks to clean up resources
•
How to use
•
The different between checked and unchecked exceptions
•
How to create a new exception type and use it in your code
try-catch-resources
block
•
How to use auto-closeable resources using a
•
How to access the stack frames of a thread
What Is an Exception?
An exception is a condition that may arise during the execution of a Java program when a normal path of execution is
not defined. For example, a Java program may encounter a numeric expression that attempts to divide an integer by
zero. Such a condition may occur during the execution of the following snippet of code:
int x = 10, y = 0, z;
z = x/y; // Divide-by-zero
The statement
z = x/y
attempts to divide
x
by
y
. Because
y
is zero, the result of
x/y
is not defined in Java. Note
that dividing a floating-point number by zero, for example
9.5/0.0
, is defined and it is infinity. In generic terms, the
abnormal condition, such as dividing an integer by zero, can be phrased as follows:
An error occurs when a Java program attempts to divide an integer by zero.
The Java programming language describes the above error condition differently. In Java, it is said
An exception is thrown when a Java program attempts to divide an integer by zero.
Practically, both statements mean the same thing. They mean that an abnormal condition in a program has occurred.
What happens after the abnormal condition occurs in a program? You need to handle such an abnormal
condition in the program. One of the ways to handle it is to check for all possibilities that may lead to an abnormal
condition, before performing the action. You may rewrite the above code as follows:
int x = 10, y = 0, z;
if (y == 0) {