0% found this document useful (0 votes)
35 views20 pages

Lecture 16 - Exception Handling

Uploaded by

devmith2005
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
35 views20 pages

Lecture 16 - Exception Handling

Uploaded by

devmith2005
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 20

ICT 1411

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;

public class DivisionExample {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.println("Enter numerator: ");


int numerator = scanner.nextInt();
System.out.println("Enter denominator: ");
int denominator = scanner.nextInt();

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();
}

public static int divide(int numerator, int denominator) {


return numerator / denominator;
}
}
• Place the code that might generate an exception inside the try block.
• Every try block is followed by a catch block.
• When an exception occurs, it is caught by the catch block.
• The catch block cannot be used without the try block.
finally
• The finally block is always executed no matter whether there is an exception or not.
• The finally block is optional.
• And, for each try block, there can be only one finally block.

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];
}

public static void main(String[] args) {


ArrayProcessor processor = new ArrayProcessor();
int[] array = {1, 2, 3, 4, 5};
try {
int element = processor.getElementAtIndex(array, 10); // This will throw an exception
System.out.println("Element at index 10: " + element);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception caught: " + e.getMessage());
}
}
}
• Throws
• The throws keyword is used in method declarations to indicate that the
method may throw certain types of exceptions.
• It specifies the exceptions that the method can throw, but it doesn't handle
them.
• Instead, it delegates the responsibility of handling exceptions to the caller of
the method.
• If a method declares that it throws a checked exception, the caller must
handle it using a try-catch block or propagate it further using the throws
clause.
public class ArrayProcessor {
public int getElementAtIndex(int[] array, int index) throws ArrayIndexOutOfBoundsException {
if (index < 0 || index >= array.length) {
throw new ArrayIndexOutOfBoundsException("Index out of bounds: " + index);
}
return array[index];
}

public static void main(String[] args) {


ArrayProcessor processor = new ArrayProcessor();
int[] array = {1, 2, 3, 4, 5};
try {
int element = processor.getElementAtIndex(array, 10); // This will throw an exception
System.out.println("Element at index 10: " + element);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception caught: " + e.getMessage());
}
}
}
END

You might also like