CHAPTER 7
EXCEPTIONS
Topics
Introduction
Types of Exceptions
Exception handling
Java's Exception Hierarchy
Coding Exceptions
◼ Try – catch mechanism
◼ Passing exception
Some common exceptions
Declaring your own Exception
…
An exception is a problem that arises during the execution of
a program. It is a representation of an error condition or a
situation that is not the expected result of a method/program.
An Exception is an unwanted event that interrupts the normal
flow of the program.
When an exception occurs program execution gets terminated.
In such cases we get a system generated error message.
The good thing about exceptions is that they can be handled in
Java. By handling the exceptions we can provide a meaningful
message to the user about the issue rather than a system
generated message, which may not be understandable to a
user.
Introduction
▪There are three categories of errors: syntax errors, runtime
errors, and logic errors.
Syntax 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.
▪ This chapter introduces using exception handling to deal with
runtime error.
…
An exception can occur for various reasons:
Attempting to divide by zero (arithmetic exception)
Reading a decimal value when an integer is expected (number
format exception)
Attempting to write to a file that doesn't exist (I/O exception).
Access an element past the end of an array.
(ArrayIndexOutOfBoundsException)
or referring to a nonexistent character in a string
(StringIndexOutOfBounds exception).
Invoke a method on a reference variable with null value.
(NullPionterException)
A network connection has been lost in the middle of
communications, or the JVM has run out of memory.
…
Some of these exceptions are caused by user error,
others by programmer error, and others by physical
resources that have failed in some manner.
No matter how well-designed a program is, there is
always the chance that some kind of error will arise
during its execution.
A progarm that does not provide code for catching and
handling exceptions will terminate abnormally, and may
cause serious problems.
A well-designed program should include code to guard
against errors and other exceptional conditions when
they arise.
…
This code should be incorporated into the program
from the very first stages of its development.
That way it can help identify problems during
development.
In Java, the preferred way of handling such
conditions is to use exception handling - a divide-
and-conquer approach that separates a program's
normal code from its error-handling code.
Java's Exception Hierarchy
The Java class library contains a number of predefined
exceptions.
All exception classes are subtypes of the
[Link] class.
The exception class is a subclass of the Throwable class.
Other than the exception class there is another subclass
called Error which is derived from the Throwable class.
The Throwable class is contained in the [Link]
package and subclass of Throwable are contained in
various packages.
Example: Errors related to GUI components are included
in the [Link]
…
Errors are not normally trapped from the Java
programs. These conditions normally happen in case
of severe failures, which are not handled by the
java programs.
Errors are generated to indicate errors generated
by the runtime environment.
Example : JVM is out of Memory. Normally
programs cannot recover from errors.
Java's Exception Classes
ClassNotFoundExceptio
n
IOException
ArithmeticExceptio
n
Exception AWTException
NullPointerExceptio
n
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException
LinkageError Several more classes
VirtualMachineErro
r
Error
AWTError
Several more classes
Categories of Exception
To understand how exception handling works in Java, you need to
understand the two categories of exceptions:
Checked exceptions:
◼ During checked exceptions :the compiler checks them during
compilation to see whether the programmer has handled them or not.
If these exceptions are not handled/declared in the program, you will
get compilation error. For example, SQLException, IOException,
ClassNotFoundException etc.
◼ A checked exception is one that can be analyzed (can’t be ignored)
by the Java compiler.
◼ That is when the compiler encounters one of these exceptions it checks
whether the program either handles or declares the exception.
◼ A checked exception is an exception that is typically a user error or a
problem that cannot be foreseen by the programmer.
◼ For example, if a file is to be opened, but the file cannot be found,
an exception occurs.
…
Runtime exceptions (Unchecked Exceptions):
◼ Runtime exception is an exception that occurs that probably could
have been avoided by the programmer.
◼ As opposed to checked exceptions, runtime exceptions are ignored at
the time of compilation.
◼ it’s the responsibility of the programmer to handle these exceptions
and provide a safe exit.
◼ RuntimeException is caused by programming errors, such as bad
casting, accessing an out-of-bounds array, and numeric errors
◼ Example of unchecked exception is ArithmeticException,
NullPointerException, ArrayIndexOutOfBoundsException etc.
Errors (Unchecked Exceptions) :
◼ These are not exceptions at all, but problems that arise beyond the
control of the user or the programmer.
◼ Errors are typically ignored in your code because you can rarely do
anything about an error.
◼ For example, if a stack overflow occurs, an error will arise. They are
also ignored at the time of compilation.
Exception Handling
Exception handling is the technique of catching the
exceptions that might be thrown some time in the
future during runtime.
Exceptions can be handled in traditional way of
handling errors within a program with Java's
default exception-handling mechanism or using
Exception class defined in Java API.
…
Traditional way of Handling Errors
Consider the following example
public double avgFirstN(int N) {
int sum = 0;
for(int k = 1; k <= N; k++)
sum += k;
return sum/N; // What if N is 0?
}
…
public double avgFirstN(int N) {
int sum = 0;
if (N <= 0) {
[Link]("ERROR avgFirstN: N <= 0. Program terminating.")
[Link](0); The error-handling code is built
} right into the algorithm
for (int k = 1; k <= N; k++)
sum += k;
return sum/N; // What if N is 0?
} // avgFirstN()
This method has several problems
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.
Some Common Exceptions
…
How do you handle exceptions?
Java exception handling is managed via five
keywords: try, catch, throw, throws, and finally.
Java exception handling is a mechanism for
handling exception by detecting and responding to
exceptions in a systematic, uniform and reliable
manner.
Exception handling is accomplished through the “try
– catch” mechanism, or by a “throws or throw”
clause in the method declaration.
…
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
is placed in a block of code starting with the “catch”
keyword.
You might like to think of these as "try to do this task"
and if there is an exception "catch the exception and
do something about it".
A try/catch block is placed around the code that
might generate an exception.
…
Code within a try/catch block is referred to as
protected code.
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)
Generally, the try statement contains and guards a
block of statements.
…
Syntax of try catch
try{
codes that may throw exception(s)
}
catch (exception_type1 identifier){
//how do you want to deal with this
exception
}
catch (exception_type2 identifier){
//how do you want to deal with this
exception
}
// you can use multiple catches to
handle different exceptions
…
A catch statement involves declaring the type of exception
you are trying to catch.
If an exception occurs in protected code, the catch block
(or blocks) that follows the try is checked.
If the type of exception that occurred is listed in a catch
block, the exception is passed to the catch block much as
an argument is passed into a method parameter.
Only one catch block, that is the first applicable one, will
be executed.
If no exceptions arise during the execution of the try block,
the catch blocks are skipped.
…
import [Link];
public class ExceptionDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter an integer: ");
int number = [Link]();
If an exception occurs on this line,
the rest of the lines in the method // Display the result
are skipped and the program is
[Link](
terminated.
"The number entered is " + number);
}
}
Terminated.
…
…
import [Link].*;
public class HandleExceptionDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
boolean continueInput = true;
do {
try {
[Link]("Enter an integer: ");
int number = [Link]();
If an exception occurs on this line,
the rest of lines in the try block are
skipped and the control is // Display the result
transferred to the catch block. [Link](
"The number entered is " + number);
continueInput = false;
}
catch (InputMismatchException ex) {
[Link]("Try again. (" +
"Incorrect input: an integer is required)");
[Link](); // discard input
}
} while (continueInput);
}
}
…
…
Example:
java import [Link].*;
public class ExcepTest{
public static void main(String args[]){
try{
int a[] = new int[2];
[Link]("Access element three :"+ a[3]);
}
catch(ArrayIndexOutOfBoundsException e){
[Link]("Exception thrown :" + e);
}
[Link]("Out of the block");
}
}
…
Example
…
Output:
Exception thrown :[Link]: 3 Out
of the block
Suppose the main method invokes method1, method1
invokes method2, method2 invokes method3, and an
exception occurs in method3 .
main method { method1 { method2 { An exception
... ... ... is thrown in
try { try { try { method3
... ... ...
invoke method1; invoke method2; invoke method3;
statement1; statement3; statement5;
} } }
catch (Exception1 ex1) { catch (Exception2 ex2) { catch (Exception3 ex3) {
Process ex1; Process ex2; Process ex3;
} } }
statement2; statement4; statement6;
} } }
…
If method3 cannot handle the exception, mehtod3 is
aborted and the control is returned to method2.
If the exception type is Excetion3, it caught by the
catch block for handling exception ex3 in method2.
Statement5 is skipped, and statement6 is executed.
If exception type is not Exception1, Exception2, or
Exception3, the exception is not caught and the
program terminates. Statement1 and Statement2
are not executed
…
• A catch block will catch exceptions of the class
specified, including any exceptions that are
subclasses of the one specified.
• The order in which exceptions are specified in
catch blocks is important.
• A compilation error will result if a catch block for a
superclass type appears before a catch block for
a subclass type .
( A more specific catch block must precede a more
general one in the source. Failure to meet this
ordering requirement causes a compiler error. )
…
try { try {
..….. ..…..
} }
catch(Exception ex){ catch(RuntimeException ex){
……. ……
} }
catch (RuntimeException ex) { catch (Exception ex ) {
…….. ……..
} }
(a) Wrong order (b) Correct Order
…
Example:
Here is code segment showing how to use multiple try/catch
statements.
try {
file = new FileInputStream(fileName);
x = (byte) [Link]();
}
catch(IOException i) {
[Link]();
return -1;
}
catch(FileNotFoundException f) { //Not valid!
[Link]();
return -1;
}
…
The finally Keyword
The finally keyword is used to create a block of
code that follows a try block.
A finally block of code always executes, whether
or not an exception has occurred.
Using a finally block allows you to run any cleanup-
type statements that you want to execute, no matter
what happens in the protected code.
A finally block appears at the end of the catch
blocks and has the following syntax:
…
try{
codes that may throw exception(s)
}
catch (exception_type1 identifier){
//how do you want to deal with this exception
}
catch (exception_type2 identifier){
//how do you want to deal with this exception
}
// you can use multiple catches to handle different
exceptions
finally {
// code that must be executed under successful or
unsuccessful conditions
}
…
• The finally block always executed regardless an
exception or not except the following conditions:
▪ The death of the thread
▪ The use of [Link]( )
▪ Turning off the power to the CPU
▪ An exception arising in the finally block itself
…
Example:
public class ExcepTest{
public static void main(String args[]){
int a[] = new int[2];
try{
[Link]("Access element three :" + a[3]);
}
catch(ArrayIndexOutOfBoundsException e){
[Link]("Exception thrown :" + e);
}
finally{
a[0] = 6;
[Link]("First element value: " +a[0]);
[Link]("The finally statement is executed");
}
}
}
…
Output:
Exception
thrown:[Link]
n: 3
First element value: 6
The finally statement is executed
…
Note the following:
A catch clause cannot exist without a try statement.
It is not compulsory to have finally clauses when
ever a try/catch block is present.
The try block cannot be present without either catch
clause or finally clause.
Any code cannot be present in between the try,
catch, finally blocks.
…
The throws/throw Keywords:
In any method that might throw an exception, you may
declare the method as “throws” that exception, and
thus avoid handling the exception yourself.
The throws keyword appears at the end of a method's
signature.
public void myMethod()throws IOException
Example
public void myMethod throws IOException {
normal code with some I/O
}
Every method must declare the types of checked
exceptions it might throw using throws keyword.
…
A method can declare that it throws more than
one exception, in which case the exceptions are
declared in a list separated by commas.
public void myMethod() throws Exception1,
Exception2, …. ExceptionN
…
Java forces you to deal with checked exceptions.
If a method declares a checked exception (i.e., an
exception other than Error or RuntimeException), you
must invoke it in a try-catch block or declare to throw
the exception in the calling method.
…
Example
Suppose that method p1 invokes method p2 and p2 may throw a
checked exception (e.g., IOException).
void p1() { void p1() throws IOException {
try { p2();
p2(); }
}
catch (IOException ex) {
...
}
}
…
▪ When the program detects an error, the program can
create an instance of an appropriate exception type
and throw it by using the throw keyword.
▪ Here is an example,
throw new TheException();
TheException ex = new TheException();
throw ex;
Example;
public void openFile(String fileName) throws IOException{
open the file using the input file name;
if (can not open file) throw new IOException();
read the file,
}
…
In general, each exception class in the java API has
at least two constructor: a no-arg constructor, and a
constructor with a String arguments that describes
the exception.
This argument is called the exception message,
which can be obtained using getMessage().
public void setRadius(double newRadius)
throws IllegalArgumentException {
if (newRadius >= 0)
radius = newRadius;
else
throw new IllegalArgumentException(
"Radius cannot be negative");
}
…
Getting Information from Exception
An Exception object contains valuable information
about the exception. You may use the following
instance methods in the [Link] class
to get information regarding the exception.
public String getMessage()
Returns the message of this object or null if there is
no detail message.
…
public String toString()
Returns the concatenation of three strings:
The full name of the exception class
+
“:” (colon and space)
+
The getMessage() method.
public void printStackTrace()
Prints theThrowable object and its call stack trace
information on the console.
Declaring your own Exception
You can create your own exceptions in Java. Keep the
following points in mind when writing your own
exception classes:
All exceptions must be a child of Throwable.
If you want to write a checked exception that is
automatically enforced by the Handle or Declare
Rule, you need to extend the Exception class.
If you want to write a runtime exception, you need to
extend the RuntimeException class.
You can define our own Exception class as below:
class MyException extends Exception{ …}
…
You just need to extend the Exception class to
create your own Exception class. These are
considered to be checked exceptions.
The following InsufficientFundsException class is
a user-defined exception that extends the
Exception class, making it a checked exception.
…
// File Name [Link]
import [Link].*;
public class InsufficientFundsException
extends Exception{
private double amount;
public InsufficientFundsException(double
amount){
[Link] = amount;
}
public double getAmount(){
return amount;
}
}
…
To demonstrate using our user-defined exception, the
following CheckingAccount class contains a withdraw()
method that throws an InsufficientFundsException.
// File Name [Link]
import [Link].*;
public class CheckingAccount{
private double balance;
private int number;
public CheckingAccount(int number) { [Link] = number; }
public void deposit(double amount) { balance +=
amount; }
public double getBalance() { return balance; }
public int getNumber() { return number; }
…
public void withdraw(double amount) throws
InsufficientFundsException {
if(amount <= balance) {
balance-= amount;
}
else{
double needs = amount - balance;
throw new InsufficientFundsException(needs);
}
}
}
The following BankDemo program demonstrates invoking the
deposit() and withdraw() methods of CheckingAccount.
…
public class BankDemo{
public static void main(String [] args) {
CheckingAccount c = new CheckingAccount(101);
[Link]("Depositing $500...");
[Link](500.00);
try {
[Link]("\nWithdrawing $100...");
[Link](100.00);
[Link]("\nWithdrawing $600...");
[Link](600.00);
}catch(InsufficientFundsException e) {
[Link]("Sorry, but you are short $“ + [Link]());
[Link]();
}
}
}
…
Compile all the above three files and run BankDemo, this
would produce following result.
Depositing $500...
Withdrawing $100...
Withdrawing $600...
Sorry, but you are short $200.0
InsufficientFundsException
at [Link]([Link])
at [Link]([Link])
Creating a better error message for debugging:
[Link]()
Instead of using Java's [Link]() method to print
errors during the debugging process, you can get more
information about the error process if you print a stack
trace from the exception.
The snippet of source code shown below shows how to
print the stack trace.
try {
// try to open the non-existent file
} catch (IOException e) {
// you handle the exception here
[Link]();
}
…
As a final point - don't forget the [Link]()
method - because the error message is not
automatically printed to the screen.