Lecture 16 - Exception Handling
Lecture 16 - Exception Handling
Object Oriented
Programming
Lecture 16
Exception Handling
Exception?
• Exception is an abnormal condition.
• They abnormally terminate the execution of a program.
• Therefore, they needs to be handled.
• The Exception Handling in Java is one of the powerful mechanism to handle the
runtime errors so that the normal flow of the application can be maintained.
Hierarchy of Java
Exception classes
• The java.lang.Throwable
class is the root class of
Java Exception hierarchy
inherited by two
subclasses: Exception and
Error.
• The hierarchy of Java
Exception classes is given
below:
Types of Java Exceptions
• There are mainly two types of exceptions: checked and unchecked. An error
is considered as the unchecked exception. However, according to Oracle,
there are three types of exceptions namely:
o Checked Exception
o Unchecked Exception
o Error
Checked Exception
• The classes that directly inherit the Throwable class except RuntimeException and
Error are known as checked exceptions.
• Ex: IOException SQLException, etc.
• Checked exceptions are checked at compile-time.
Unchecked Exception
• The classes that inherit the RuntimeException are known as
unchecked exceptions.
• Ex: ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsEx
ception, etc.
• Unchecked exceptions are not checked at compile-time, but they are
checked at runtime.
Error
• Error is irrecoverable.
• Ex: OutOfMemoryError, VirtualMachineError, AssertionError etc.
Approaches to Handle Exceptions
• Approaches to handle exceptions in Java.
o try...catch block
o finally block
o throw and throws keyword
try....catch
• The try-catch block is used to handle exceptions in Java.
• Syntax of try...catch block:
try {
// code
}
catch(Exception e) {
// code
}
import java.util.Scanner;
try {
int result = divide(numerator, denominator);
System.out.println("Result of division: " + result);
} catch (ArithmeticException e) {
System.out.println("Exception caught: Cannot divide by zero.");
}
scanner.close();
}
try {
//code
}
catch (ExceptionType1 e1) {
// catch block
}
finally {
// finally block always executes
}
Note:
• It is a good practice to use the finally block.
• It is because it can include important cleanup codes like,
o code that might be accidentally skipped by return, continue or break
o closing a file or connection
throw and throws
• throw
• The throw keyword is used to explicitly throw an exception within a method or
block of code.
• It is followed by an instance of an exception class or subclass.
• When throw is encountered, the control flow is immediately transferred to
the nearest enclosing catch block or to the method's caller if no
appropriate catch block is found.
public class ArrayProcessor {
public int getElementAtIndex(int[] array, int index) {
if (index < 0 || index >= array.length) {
throw new ArrayIndexOutOfBoundsException("Index out of bounds: " + index);
}
return array[index];
}