Lecture 7
Lecture 7
Programming
with Java II
Email: [email protected]
Lecture outcomes
• Exception handling motivation
• Exception types
• Declaring exceptions
• Throwing exceptions
• Catching exceptions
• 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 4
Example with Runtime Error
Handled using an if statement
import java.util.Scanner;
public class QuotientWithIf {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Prompt the user to enter two integers
System.out.print("Enter two integers: ");
int number1 = input.nextInt(); int number2 = input.nextInt();
if (number2 != 0)
System.out.println(number1 + " / " + number2 + " is " + (number1 / number2));
else
System.out.println("Divisor cannot be zero ");
}
Dr. Mohamed K. Hussein 5
}
Example with Handled Runtime Error
using method
import java.util.Scanner;
public class QuotientWithMethod {
public static int quotient(int number1, int number2) {
if (number2 == 0) {
System.out.println("Divisor cannot be zero");
System.exit(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(System.in); program—the caller should decide whether to
System.out.print("Enter two integers: "); terminate the program
int number1 = input.nextInt();
int number2 = input.nextInt();
int result = quotient(number1, number2);
System.out.println(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(System.in);
• It enables a method to throw an exception to its
System.out.print("Enter two integers: ");
caller.
int number1 = input.nextInt();
• Without this capability, a method must handle
int number2 = input.nextInt();
the exception or terminate the program.
try {
int result = quotient(number1, number2);
System.out.println(number1 + " / " + number2 + " is “ + result);
}
catch (ArithmeticException ex) {
System.out.println("Exception: an integer " + "cannot be divided by zero ");
}
System.out.println("Execution continues ...");
} Dr. Mohamed K. Hussein 7
}
Exception
• The execution of a throw statement is called throwing an exception.
• The statement for invoking the method is contained in a try block and a
catch block.
Exception NullPointerException
RuntimeException
IndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException
Error VirtualMachineError
ArithmeticException
IOException
Exception NullPointerException
RuntimeException
IndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException
Error VirtualMachineError
ArithmeticException
IOException
Exception NullPointerException
RuntimeException
IndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException
unchecked exceptions.
• meaning that the compiler forces the programmer to check and deal
• Example:
throw new TheException();
TheException ex = new TheException();
throw ex
• 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.
Call Stack
method3
method2 method2
• 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).
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;
Next statement;
Next statement;
Next statement;
Next statement;
Next statement;
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
sufficient.
subclass of Exception.
Dr. Mohamed K. Hussein 40
Example
public class InvalidRadiusException extends Exception {
private double radius;
• 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)