Exception Handling (2)
Exception Handling (2)
An exception (or exceptional event) is a problem that arises during the execution of a
program.
When an Exception occurs the normal flow of the program is disrupted and the
program/Application terminates abnormally, therefore, these exceptions are to be handled
In Java, an exception is an event that disrupts the normal flow of the program. It is an object
which is thrown at runtime.
An exception can occur for many different reasons. Following are some scenarios where an
exception occurs.
Some of these exceptions are caused by user error, others by programmer error, and others
by physical resources that have failed in some manner.
The Exception Handling in Java is one of the powerful mechanisms to handle the runtime
errors so that the normal flow of the application can be maintained.
statement 1;
Suppose there are 8 statements in a Java
statement 2; program and an exception occurs at
statement 3; statement 5; the rest of the code will not
statement 4; be executed, i.e., statements 6 ,7,8 will
not be executed. However, when we
statement 5;//exception occurs
perform exception handling, the rest of
statement 6;
the statements will be executed. That is
statement 7;
why we use exception handling in Java.
statement 8;
Hierarchy of Java Exception classes
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:
● Checked Exception
Exceptions that are checked at compile-time (e.g., IOException, SQLException).
● Unchecked Exception
Exceptions that are not checked at compile-time (e.g., ArithmeticException,
NullPointerException)
● Error
Severe problems that are not usually handled by the application (e.g., OutOfMemoryError).
.
Checked Exceptions in Java
A checked exception (also called a logical exception) in Java is something that has gone
wrong in your code and is potentially recoverable. For example, if there’s a client error when
calling another API, we could retry from that exception and see if the API is back up and
running the second time. A checked exception is caught at compile time so if something
throws a checked exception the compiler will enforce that you handle it.
The most common runtime exception is the good old NullPointerException which is when
you are trying to access a variable or object that doesn’t exist.
1. Handling Exceptions
output
Exception caught: java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for
length 3
Program continues...
2. Declaring Exceptions
Purpose: Allows a method to specify which exceptions it might throw, ensuring that callers
of the method are aware of and can handle potential exceptions.
Syntax:
void methodName() throws ExceptionType {
// method code
}
Example:
import java.io.*;
Purpose: Allows the programmer to explicitly throw an exception when a certain condition
is met.
Syntax: throw new ExceptionType("Error message");
Example:
Purpose: Allows a program to catch and handle exceptions, preventing the program from
terminating unexpectedly.
Syntax:
try {
// code that may throw an exception
} catch (ExceptionType e) {
// code to handle the exception
}
Example:
Common Methods:
Example:
public class ExceptionInfo {
try {
numbers[10] = 50;
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
}
6. The finally Clause
Purpose: The finally block is used to execute important code such as closing resources,
regardless of whether an exception is handled or not.
Syntax:
try {
// code that may throw an exception
} catch (ExceptionType e) {
// code to handle the exception
} finally {
// code to be executed no matter what
}
Example:
import java.io.*;
Types of Exceptions
1. Checked Exceptions:
● These are exceptions that the compiler checks at compile-time. If a
method can throw a checked exception, it must either handle it with a
try-catch block or declare it in its method signature using the throws
keyword.
● Examples include:: Issues related to input/output operations.
2. Unchecked Exceptions:
● These exceptions are not checked at compile-time but occur at runtime.
They extend RuntimeException.
● Examples include:: Occurs when an arithmetic operation fails, such as
division by zero.
Examples:
1. ArithmeticException
int x = 10;
int y = 0;
try {
} catch (ArithmeticException e) {
}
}
Output:
Error: / by zero
2. NullPointerException
This exception occurs when trying to access an object or variable that has
not been initialized (i.e., it is null).
try {
Output:
3. ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
Output:
4. NumberFormatException
try {
} catch (NumberFormatException e) {
Output:
try {
} catch (IllegalArgumentException e) {
if (age < 0) {
Output:
3. Errors:
● These are serious issues that applications should not try to catch. They
usually indicate problems with the Java Runtime Environment (JRE) itself.
● Examples include:: Occurs when the JVM runs out of memory.
● try: A block of code that may throw an exception is wrapped in a try block.
● catch: This block catches and handles exceptions thrown by the try block.
● finally: This block executes code after the try-catch blocks, regardless of whether
an exception occurred or not.
● throw: Used to explicitly throw an exception.
● throws: Declares that a method can throw one or more exceptions.
Example Code
Here’s a simple example demonstrating exception handling in Java:
Error: / by zero
Execution completed.
In this example:
● The divide method attempts to divide two integers. If the denominator is zero, it
throws an ArithmeticException.
● The exception is caught in the catch block, which prints an error message.
● The finally block executes regardless of whether an exception occurred,
indicating that execution is complete.
Conclusion
Understanding and effectively managing exceptions in Java is essential for creating
reliable applications. By using appropriate handling mechanisms and being aware of the
types of exceptions that can occur, developers can ensure their programs run smoothly
and handle errors gracefully.
===============================================================
Sample Questions
● Write a Java program that reads a file named input.txt and displays its contents.
Handle exceptions for file not found and I/O errors.
● Create a program that takes two integers as input from the user and performs
division. Handle ArithmeticException for division by zero
● Implement a method that reads integers from a file named numbers.txt, calculates
their average, and handles exceptions for I/O and number format issues.
Ref