Object Oriented Programming
[ECEg-3102]
Chapter Six:
Exception Handling
Compiled by Amanuel Z. & Fasika T.
Outline
▪ Introduction by example
▪ try- catch mechanism
▪ Exception classes
▪ The finally Block
2
Introduction by example
▪ Runtime errors occur while a program is running if the
environment detects an operation that is impossible to carry out.
3
Cont’d...
▪For example, if you access an array using an index out of
bounds, your program will get a runtime error with an
ArrayIndexOutOfBoundsException .
▪ To read data from a file, you need to create a Scanner object using
new Scanner(new File(filename)).
• If the file does not exist, your program will get a run-time error with a
FileNotFoundException .
4
Cont’d...
▪In Java, runtime errors are caused by exceptions.
▪An exception is an object that represents an error or a condition
that prevents execution from proceeding normally.
▪If the exception is not handled, the program will terminate
abnormally.
5
Cont’d...
▪How can you handle the exception so that the program can
continue to run or else terminate gracefully?
▪To demonstrate exception handling, including how an exception
object is created and thrown,
• we begin with an example that reads in two integers and
displays their quotient.
6
Cont’d...
import [Link];
Enter two integers: 5 2
public class Quotient {
5/2 is 2
public static void main(String[] args) {
Scanner input = new Scanner([Link]);
[Link]("Enter two integers: ");
int number1 = [Link]();
int number2 = [Link]();
[Link](number1 + " / " + number2 + " is " + ( number1 / number2 ));
} Enter two integers: 3 0
} Exception in thread "main" [Link]: / by zero at
[Link]([Link])
7
Cont’d...
▪If you entered 0 for the second number, a runtime error
would occur, because you cannot divide an integer by 0 .
• Recall that a floating-point number divided by 0 does not
raise an exception.
▪A simple way to fix the error is to add an if statement to
test the second number.
8
Cont’d...
public class QuotientWithIf {
public static void main(String[] args) {
Scanner input = new Scanner([Link]);
[Link]("Enter two integers: ");
int number1 = [Link]();
int number2 = [Link]();
if (number2 != 0)
[Link](number1 + " / " + number2 + " is " + ( number1 / number2 ));
else
[Link]("Divisor cannot be zero ");
} Enter two integers: 5 0
} Divisor cannot be zero 9
Cont’d...
▪ In order to demonstrate the concept of exception handling,
including how to create, throw, catch, and handle an
exception, we rewrite the above program as shown below.
10
Cont’d...
import [Link]; Output:
public class QuotientWithException { Enter two integers: 5 3
public static void main(String[] args) {
5 / 3 is 1
Scanner input = new Scanner([Link]);
[Link]("Enter two integers: "); Execution continues ...
int number1 = [Link](); Enter two integers: 5 0
int number2 = [Link](); Exception: an integer cannot be divided by zero
try { Execution continues ...
if (number2 == 0)
throw new ArithmeticException("Divisor cannot be zero");
[Link](number1 + " / " + number2 + " is " + (number1 / number2)); }
catch (ArithmeticException ex) {
[Link]("Exception: an integer " + "cannot be divided by zero "); }
[Link]("Execution continues ...");
}
}
11
try-catch Mechanism
▪ The basic way of handling exceptions in Java consists of the try-
throw-catch trio.
▪ The try block contains the code for the basic algorithm.
• It tells what to do when everything goes smoothly
▪ It is called a try block because it "tries" to execute the case
where all goes as planned.
12
Cont’d...
▪A try block has the following syntax:
try{
CodeThatMayThrowAnException
13
Cont’d...
▪ A try block can also contain code that throws an exception if
something unusual happens
try{
CodeThatMayThrowAnException
throw new ExceptionClassName (PossiblySomeArguments);
14
Cont’d...
▪ When an exception is thrown, the execution of the
surrounding try block is stopped.
• Normally, the flow of control is transferred to another portion of
code known as the catch block.
▪ The value thrown is the argument to the throw operator,
and is always an object of some exception class.
▪ The execution of a throw statement is called throwing an
exception.
15
Cont’d...
▪ A throw statement is similar to a method call:
throw new ExceptionClassName(SomeString);
• In the above example, the object of class ExceptionClassName is
created using a string as its argument.
• This object, which is an argument to the throw operator, is the
exception object thrown.
▪ Instead of calling a method, a throw statement calls a catch
block.
16
Cont’d...
■ When an exception is thrown, the catch block begins execution
• The catch block has one parameter
• The exception object thrown is plugged in for the catch block
parameter
■ The execution of the catch block is called catching the
exception, or handling the exception.
• Whenever an exception is thrown, it should ultimately be handled (or
caught) by some catch block
17
Cont’d...
▪ The appropriate catch block immediately follows the try block;
catch(Exception e){
ExceptionHandlingCode
18
Cont’d...
■ A catch block looks like a method definition that has a parameter
of type Exception class
• It is not really a method definition
■A catch block is a separate piece of code that is executed when a
program encounters and executes a throw statement in the
preceding try block
• A catch block is often referred to as an exception handler.
• It can have at most one parameter
19
Cont’d...
catch(Exception e) {
}
▪ The identifier e in the above catch block heading is called the
catch block parameter.
20
Cont’d...
The catch block parameter does two things:
1. It specifies the type of thrown exception object that the catch block can
catch (e.g., an Exception class object above)
2. It provides a name (for the thrown object that is caught) on which it can
operate in the catch block
Note:
The identifier e is often used by convention, but any non-keyword identifier
can be used.
21
Cont’d...
When a try block is executed, two things can happen:
1. No exception is thrown in the try block
• The code in the try block is executed to the end of the block
• The catch block is skipped
• The execution continues with the code placed after the catch
block
22
Cont’d...
2. An exception is thrown in the try block and caught in the catch
block
• The rest of the code in the try block is skipped
• Control is transferred to a following catch block (in simple cases)
• The thrown object is plugged in for the catch block parameter
• The code in the catch block is executed
• The code that follows that catch block is executed (if any)
23
Exception Classes
■ Theexception is object created at the time of exceptional/error
condition which will be thrown from the program and halt normal
execution of the program.
24
Cont’d...
Figure 1: Java exceptions object hierarchy
25
Cont’d...
▪ The exception classes can be classified into three major types:
[Link] errors
[Link]
[Link] exceptions
26
Cont’d...
27
Cont’d...
28
Cont’d...
29
Cont’d...
■ Allexception types are subclasses of the built-in class
Throwable.
■ Thus, Throwable is at the top of the exception class hierarchy.
■ Immediately below Throwable are two subclasses that partition
exceptions into two distinct branches.
30
Cont’d...
1. One branch is headed by Exception.
• This classic used for exceptional conditions that user
programs should catch.
• This is also the class that you will subclass to create your own
custom exception types.
31
Cont’d...
▪ There is an important subclass of Exception, called Runtime
Exception.
• Exceptions of this type are automatically defined for the
programs that you write and include things such as division
by zero and invalid array indexing.
32
Cont’d...
2. The other branch is topped by Error, which defines exceptions
that are not expected to be caught under normal circumstances
by your program.
• Exceptions of type Error are used by the Java runtime system to
indicate errors having to do with the runtime environment, itself.
Example-Stack overflow is an example of such an error.
33
Cont’d...
Java’s exceptions can be categorized into two types:
1. Checked exceptions
2. Unchecked exceptions
▪ Generally, checked exceptions are subject to the catch or
specify a requirement, which means they require catching or
declaration. This requirement is optional for unchecked
exceptions.
▪ Code that uses a checked exception will not compile if the
catch or specify rule is not followed.
34
Cont’d...
Unchecked exceptions come in two types:
1. Errors
2. Runtime exceptions
35
Cont’d...
1. Checked Exceptions
▪ Exceptions which are checked during compile time are called
checked exceptions, meaning that the compiler forces the
programmer to check and deal with the exceptions.
▪ Checked exceptions are the type that programmers should
anticipate and from which programs should be able to recover.
36
Cont’d...
▪ All Java exceptions are checked exceptions except those of
the Error and RuntimeException classes and their subclasses.
▪ A checked exception is an exception which the Java source
code must deal with, either by catching it or declaring it to be
thrown.
▪ Checked exceptions are generally caused by faults outside of
the code itself missing resources, networking errors, and
problems with threads come to mind.
37
Cont’d...
▪ These could include subclasses of FileNotFoundException, UnknownHostException,
etc.
Popular Checked Exceptions:
Name Description
IOException While using file input/output stream related exception
SQLException. While executing queries on database related to SQL syntax
DataAccessException Exception related to accessing data/database
ClassNotFoundException Thrown when the JVM can’t find a class it needs, because of a
command-line error, a classpath issue, or a missing .class file
InstantiationException Attempt to create an object of an abstract class or interface.
38
Cont’d...
2. Unchecked Exceptions
▪ Exceptions which are not checked for during compile time are called
unchecked exception.
▪ Unchecked exceptions inherit from the Error class or the
RuntimeException class.
▪ Many programmers feel that you should not handle these exceptions in
your programs because they represent the type of errors from which
programs cannot reasonably be expected to recover while the program is
running.
▪ When an unchecked exception is thrown, it is usually caused by a
misuse of code - passing a null or otherwise incorrect argument.
39
Cont’d...
40
Cont’d...
Popular Unchecked Exceptions:
Name Description
NullPointerException Thrown when attempting to access an object with a reference variable whose
current value is null
ArrayIndexOutOfBound Thrown when attempting to access an array with an invalid index value (either
negative or beyond the length of the array)
IllegalArgumentException. Thrown when a method receives an argument formatted differently than the
method expects.
IllegalStateException Thrown when the state of the environment doesn’t match the operation being
attempted,e.g., using a Scanner that’s been closed.
NumberFormatException Thrown when a method that converts a String to a number receives a String
that it cannot convert.
ArithmaticException Arithmetic error, such as divide-by-zero.
41
The finally Block
▪ Occasionally, you may want some code to be executed
regardless of whether an exception occurs or is caught.
• Java has a finally clause that can be used to accomplish this
objective.
• Java finally block is always executed whether exception is
handled or not.
42
Cont’d...
▪ The syntax for the finally clause might look like this:
try{
}
catch(ExceptionClass1 e){ Java finally block follows try
or catch block.
}
finally{
CodeToBeExecutedInAllCases
}
43
Cont’d...
❑ Note: If you don't handle exception, before terminating the program,
JVM executes finally block(if any).
Why we use java finally?
▪ Finally block in java can be used to put "cleanup" code such as closing
a file, closing connection etc.
44
animation
Trace a Program Execution
Suppose no exceptions
in the statements
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
45
Cont’d...
try { The final block is
statements; always executed
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
46
Cont’d...
try { Next statement in the
statements; method is executed
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
47
Cont’d...
try {
Suppose an exception
statement1; of type Exception1 is
statement2; thrown in statement2
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
48
Cont’d...
try {
statement1; The exception is
statement2; handled.
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
49
Cont’d...
try {
statement1;
The final block is
statement2;
always executed.
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
50
Cont’d...
try {
statement1;
statement2;
statement3;
}
catch(Exception1 ex) { The next statement in the
handling ex;
method is now executed.
}
finally {
finalStatements;
}
Next statement;
51
Cont’d...
try {
statement1;
statement2 throws an
statement2;
statement3;
exception of type
} Exception2.
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
52
Cont’d...
try {
statement1; Handling exception
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
53
Cont’d...
try {
statement1;
statement2;
statement3;
} Execute the final block
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
54
Cont’d...
try {
statement1;
statement2; Rethrow the exception and
statement3; control is transferred to the
} caller
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
55
Cont’d...
Usage of Java finally
▪ Let's see the different cases where java finally block can be used.
Case 1
▪ Let's see the java finally example where exception doesn't occur.
1. class TestFinallyBlock{
2. public static void main(String args[]){
3. try{
4. int data=25/5;
5. [Link](data);
6. }
7. catch(NullPointerException e){[Link](e);}
8. finally{[Link]("finally block is always executed");}
9. [Link]("rest of the code...");
10. }
11. }
Output: finally block is always executed
rest of the code... 56
Thank You !