Object Oriented
Programming
with Java II
Dr. Mohamed K. Hussein
Lecture 7
Associate Prof., Computer Science department,
Faculty of Computers & Information Science,
Suez Canal University
Email: m_khamis@[Link]
Lecture outcomes
• Exception handling motivation
• Exception handling overview
• Exception types
• Declaring exceptions
• Throwing exceptions
• Catching exceptions
• The finally clause
• Defining custom exception classes
Dr. Mohamed K. Hussein 2
Motivation
• When a program runs into a runtime error, the program terminates
abnormally.
• Accessing an array using an index that is out of bounds.
• Entering a double value when your program expects an integer.
• Dividing by zero.
• How can you handle the runtime error so that the program can continue to run or
terminate gracefully?
Dr. Mohamed K. Hussein 3
Example with Runtime Error
public class Quotient {
public static void main(String[] args) {
Scanner input = new Scanner([Link]);
// Prompt the user to enter two integers
[Link]("Enter two integers: ");
int number1 = [Link]();
int number2 = [Link]();
[Link](number1 + "/" + number2 + " = " + (number1/number2));
}
}
Dr. Mohamed K. Hussein 4
Example with Runtime Error
Handled using an if statement
import [Link];
public class QuotientWithIf {
public static void main(String[] args) {
Scanner input = new Scanner([Link]);
// Prompt the user to enter two integers
[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 ");
}
Dr. Mohamed K. Hussein 5
}
Example with Handled Runtime Error
using method
import [Link];
public class QuotientWithMethod {
public static int quotient(int number1, int number2) {
if (number2 == 0) {
[Link]("Divisor cannot be zero");
[Link](1);
}
• If number2 is 0, it cannot return a value, so the
return number1 / number2;
program will terminate.
}
• This is clearly a problem.
public static void main(String[] args) { • You should not let the method terminate the
Scanner input = new Scanner([Link]); program—the caller should decide whether to
[Link]("Enter two integers: "); terminate the program
int number1 = [Link]();
int number2 = [Link]();
int result = quotient(number1, number2);
[Link](number1 + " / " + number2 + " is " + result);
}
Dr. Mohamed K. Hussein 6
}
Using Exception
public class QuotientWithException {
public static int quotient(int number1, int number2) {
if (number2 == 0) throw new ArithmeticException("Divisor cannot be zero");
return number1 / number2;
}
• Now you see the advantages of using exception
public static void main(String[] args) {
handling.
Scanner input = new Scanner([Link]);
• It enables a method to throw an exception to its
[Link]("Enter two integers: ");
caller.
int number1 = [Link]();
• Without this capability, a method must handle
int number2 = [Link]();
the exception or terminate the program.
try {
int result = quotient(number1, number2);
[Link](number1 + " / " + number2 + " is “ + result);
}
catch (ArithmeticException ex) {
[Link]("Exception: an integer " + "cannot be divided by zero ");
}
[Link]("Execution continues ...");
} Dr. Mohamed K. Hussein 7
}
Exception
• The execution of a throw statement is called throwing an exception.
• The exception is an object created from an exception class.
• In this case, the exception class is [Link].
• The constructor ArithmeticException(str) is invoked to construct an
exception object
• str is a message that describes the exception.
Dr. Mohamed K. Hussein 8
Exception
• When an exception is thrown, the normal execution flow is interrupted.
• To “throw an exception” is to pass the exception from one place to
another.
• The statement for invoking the method is contained in a try block and a
catch block.
• The exception is caught by the catch block.
• The code in the catch block is executed to handle the exception.
• Afterward, the statement after the catch block is executed Dr. Mohamed K. Hussein 9
Input Mismatch Exception Example
public class InputMismatchExceptionDemo {
public static void main(String[] args) {
Scanner input = new Scanner([Link]);
boolean continueInput = true;
do {
try {
[Link]("Enter an integer: ");
int number = [Link]();
[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);
}
Dr. Mohamed K. Hussein 10
}
Exception Types
• Exceptions are objects, and objects are defined using classes.
ClassNotFoundException
• The root class for exceptions is [Link]. ArithmeticException
IOException
Exception NullPointerException
RuntimeException
IndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException
Many more classes
LinkageError
Error VirtualMachineError
Many more classes
Dr. Mohamed K. Hussein 11
Exception Types
ClassNotFoundException
ArithmeticException
IOException
Exception NullPointerException
RuntimeException
IndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException
Many more classes
LinkageError
System errors are thrown by JVM and represented in the
Error class. The Error class describes internal system
Error VirtualMachineError
errors. Such errors rarely occur. If one does, there is little
you can do beyond notifying the user and trying to
Many more classes
terminate the program gracefully.
Dr. Mohamed K. Hussein 12
Exception Types
ClassNotFoundException
Exception describes errors caused by your ArithmeticException
IOException
program and external circumstances. These
Exception NullPointerException
errors can be caught and handled by your
RuntimeException
program.
IndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException
Many more classes
LinkageError
Error VirtualMachineError
Many more classes
Dr. Mohamed K. Hussein 13
Exception Types
ClassNotFoundException
ArithmeticException
IOException
Exception NullPointerException
RuntimeException
IndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException
Many more classes
LinkageError
RuntimeException is caused by programming errors,
Error VirtualMachineError such as bad casting, accessing an out-of-bounds array,
and numeric errors.
Many more classes
Dr. Mohamed K. Hussein 14
Checked Exceptions vs. Unchecked Exceptions
• RuntimeException, Error and their subclasses are known as
unchecked exceptions.
• All other exceptions are known as checked exceptions,
• meaning that the compiler forces the programmer to check and deal
with the exceptions.
Dr. Mohamed K. Hussein 15
Checked Exceptions vs. Unchecked Exceptions
• Unchecked exceptions reflect programming logic errors that are unrecoverable.
• A NullPointerException is thrown if you access an object through a reference variable
before an object is assigned to it;
• An IndexOutOfBoundsException is thrown if you access an element in an array
outside the bounds of the array.
• These are logic errors that should be corrected in the program.
• Unchecked exceptions can occur anywhere in a program.
• To avoid cumbersome overuse of try-catch blocks, Java does not mandate that you write
code to catch or declare unchecked exceptions.
Dr. Mohamed K. Hussein 16
Declaring Exceptions
• Every method must state the types of checked exceptions it
might throw.
• This is known as declaring exceptions.
method1() { declare exception
method2() throws Exception {
try {
invoke method2; if (an error occurs) {
}
catch exception catch (Exception ex) { throw new Exception(); throw exception
Process exception; }
} }
}
Dr. Mohamed K. Hussein 17
Declaring Exceptions
• System errors and runtime errors can happen to any code, Java does not require
that you declare Error and RuntimeException (unchecked exceptions) explicitly
in the method.
• However, all other exceptions thrown by the method must be explicitly declared in
the method header where the caller of the method is informed of the exception.
• To declare an exception in a method, use the throws keyword in the method
header:
public void myMethod() throws IOException
public void myMethod() throws IOException, OtherException
Dr. Mohamed K. Hussein 18
Throwing Exceptions
• When the program detects an error, the program can create an instance of
an appropriate exception type and throw it.
• This is known as throwing an exception.
• Example:
throw new TheException();
TheException ex = new TheException();
throw ex
Dr. Mohamed K. Hussein 19
Example
/** Set a new radius */
public void setRadius(double newRadius)
throws IllegalArgumentException {
if (newRadius >= 0)
radius = newRadius;
else
throw new IllegalArgumentException("Radius cannot be negative");
}
Dr. Mohamed K. Hussein 20
Catching Exceptions
• When an exception is thrown, it can be caught and handled in a try-catch
block, as follows:
try {
statements; // Statements that may throw exceptions
}
catch (Exception1 exVar1) {
handler for exception1;
}
catch (Exception2 exVar2) {
handler for exception2;
}
...
catch (ExceptionN exVar3) {
handler for exceptionN;
}
Dr. Mohamed K. Hussein 21
Catching Exceptions
• If one of the statements inside the try block throws an exception, Java skips the remaining
statements in the try block and starts the process of finding the code to handle the exception.
• The code that handles the exception is called the exception handler; it is found by propagating the
exception backward through a chain of method calls,
• starting from the current method.
• Each catch block is examined in turn, from first to last, to see whether the type of the exception object is an instance of the
exception class in the catch block.
• If so, the exception object is assigned to the variable declared, and the code in the catch block is executed.
• If no handler is found, Java exits this method, passes the exception to the method that invoked the method, and continues
the same process to find a handler.
• If no handler is found in the chain of methods being invoked, the program terminates and prints an error message on the
console.
• The process of finding a handler is called catching an exception.
Dr. Mohamed K. Hussein 22
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;
} } }
Call Stack
method3
method2 method2
method1 method1 method1
main method main method main method main method
• An exception is not caught in the current method, it is passed to its caller. The process is repeated until
the exception is caught or passed to the main method
Dr. Mohamed K. Hussein 23
Catch or Declare Checked Exceptions
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. For example, suppose that
method p1 invokes method p2 and p2 may throw a checked exception
(e.g., IOException), you have to write the code as shown in (a) or (b).
void p1() { void p1() throws IOException {
try {
p2(); p2();
}
catch (IOException ex) { }
...
}
}
(a) Dr. Mohamed K. Hussein (b) 24
public class CircleWithException {
Example
private double radius;
private static int numberOfObjects = 0; //The number of the objects created
public CircleWithException() {this(1.0); }
public CircleWithException(double newRadius) {
setRadius(newRadius);
numberOfObjects++;
}
public double getRadius() { return radius; }
public void setRadius(double newRadius) throws IllegalArgumentException {
if (newRadius >= 0)
radius = newRadius;
else
throw new IllegalArgumentException("Radius cannot be negative");
}
public static int getNumberOfObjects() {return numberOfObjects;}
public double findArea() { return radius * radius * 3.14159; }
Dr. Mohamed K. Hussein 25
}
Example
public class TestCircleWithException {
public static void main(String[] args) {
try {
CircleWithException c1 = new CircleWithException(5);
CircleWithException c2 = new CircleWithException(-5);
CircleWithException c3 = new CircleWithException(0);
}
catch (IllegalArgumentException ex) {
[Link](ex);
}
[Link]("Number of objects created: " + [Link]());
}
Dr. Mohamed K. Hussein 26
Rethrowing Exceptions
• Java allows an exception handler to rethrow the exception if the handler cannot
process the exception or simply wants to let its caller be notified of the exception.
• The syntax for rethrowing an exception may look like this:
try {
statements;
}
catch(TheException ex) {
perform operations before exits;
throw ex;
}
Dr. Mohamed K. Hussein 27
The finally Clause
• The finally clause is always executed regardless whether an exception occurred or
not.
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
Dr. Mohamed K. Hussein 28
Trace a Program Execution
Suppose no
exceptions in the
statements
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
Dr. Mohamed K. Hussein 29
Trace a Program Execution
The final block is
try { always executed
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
Dr. Mohamed K. Hussein 30
Trace a Program Execution
Next statement in the
try { method is executed
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
Dr. Mohamed K. Hussein 31
Trace a Program Execution
try { Suppose an exception
statement1; of type Exception1 is
statement2; thrown in statement2
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
Dr. Mohamed K. Hussein 32
Trace a Program Execution
try { The exception is
statement1; handled.
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
Dr. Mohamed K. Hussein 33
Trace a Program Execution
try { The final block is
statement1; always executed.
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
Dr. Mohamed K. Hussein 34
Trace a Program Execution
try { The next statement in
statement1; the method is now
statement2; executed.
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
Dr. Mohamed K. Hussein 35
Trace a Program Execution
try {
statement1; statement2 throws an
statement2; exception of type
statement3; Exception2.
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
Dr. Mohamed K. Hussein 36
Trace a Program Execution
try {
statement1; Handling exception
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
Dr. Mohamed K. Hussein 37
Trace a Program Execution
try {
statement1; Execute the final block
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
Dr. Mohamed K. Hussein 38
Trace a Program Execution
try {
statement1; Rethrow the exception
statement2; and control is
statement3; transferred to the caller
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
Dr. Mohamed K. Hussein 39
Defining Custom Exception Classes
• Use the exception classes in the API whenever possible.
• Define custom exception classes if the predefined classes are not
sufficient.
• Define custom exception classes by extending Exception or a
subclass of Exception.
Dr. Mohamed K. Hussein 40
Example
public class InvalidRadiusException extends Exception {
private double radius;
public InvalidRadiusException(double radius) {/** Construct an exception */
super("Invalid radius " + radius);
[Link] = radius;
}
public double getRadius() {return radius;}
}
Dr. Mohamed K. Hussein 41
Example
public class CircleWithCustomException {
private double radius;
private static int numberOfObjects = 0; //The number of the objects created
public CircleWithCustomException() {this(1.0); }
public CircleWithCustomException throws InvalidRadiusException (double newRadius) {
setRadius(newRadius);
numberOfObjects++;
}
public double getRadius() { return radius; }
public void setRadius(double newRadius) throws InvalidRadiusException{
if (newRadius >= 0)
radius = newRadius;
else
throw new InvalidRadiusException(newRadius);
}
public static int getNumberOfObjects() {return numberOfObjects;}
public double findArea() { return radius * radius * 3.14159; }
} Dr. Mohamed K. Hussein 42
Example
public class TestCircleWithCustomException {
public static void main(String[] args) {
try {
new CircleWithCustomException(5);
new CircleWithCustomException(-5);
new CircleWithCustomException(0);
}
catch (InvalidRadiusException ex) {
[Link](ex);
}
[Link]("Number of objects created: " +
[Link]());
}
} Dr. Mohamed K. Hussein 43
Assignment 7
• Write a program that prompts the user to read two integers and displays their
sum. Your program should prompt the user to read the number again if the input
is incorrect. (using InputMismatchException)
• Write a program that meets the following requirements:
• Creates an array with 100 randomly chosen integers.
• Prompts the user to enter the index of the array, then displays the
corresponding element value. If the specified index is out of bounds, display
the message Out of Bounds. (using ArrayIndexOutOfBoundsException)
Dr. Mohamed K. Hussein 44
Assignment 7
• Modify the Triangle class, in Assignment 6, with three sides. In a triangle, the sum of any
two sides is greater than the other side. The Triangle class must adhere to this rule.
• Create the IllegalTriangleException class, and modify the constructor of the Triangle
class to throw an IllegalTriangleException object if a triangle is created with sides that
violate the rule:
/** Construct a triangle with the specified sides */
public Triangle(double side1, double side2, double side3)
throws IllegalTriangleException {
// Implement it
Dr. Mohamed K. Hussein 45
}
Thank you