Exception Handling in Java
Exception Handling in Java
Exception Handling in Java
Exception handling is a fundamental concept in Java that allows you to gracefully handle
errors, exceptions, and unexpected situations that can occur during the execution of a program.
In Java, exceptions are represented as objects, and the exception-handling mechanism provides
a way to deal with these exceptions and prevent the program from crashing.
Types of Exceptions:
o Checked Exceptions: These are exceptions that are checked at compile time.
You are required to either catch these exceptions using a try-catch block or
declare that your method may throw them using the throws keyword. Examples
include IOException and SQLException.
o Unchecked Exceptions: These are exceptions that are not checked at compile
time. They are subclasses of RuntimeException and don't require explicit
handling. Examples include NullPointerException and
ArrayIndexOutOfBoundsException.
Exceptions can be handled by using 5 Keywords ie, try, catch, throw, throws, and finally.
1. try-catch Blocks: To handle exceptions, we enclose the code that may throw an
exception in a try block and specify one or more catch blocks to catch and handle
specific exceptions. The catch block is executed when the corresponding exception
occurs.
try
{
// Code that may throw an exception
} catch (ExceptionType1 e1) {
// Handle ExceptionType1
} catch (ExceptionType2 e2) {
// Handle ExceptionType2
} finally {
// Optional 'finally' block for cleanup code
}
• throw Keyword: We can use the throw keyword to explicitly throw an exception when a
specific condition is met. This is useful for custom exception handling.
• if (condition) {
throw new CustomException("This is a custom exception message.");
}
• throws Keyword: If a method can potentially throw checked exceptions, you should declare
them using the throws keyword in the method signature. The caller of the method is then
responsible for handling or declaring these exceptions.
• finally Block: The finally block is used for cleanup code that should be executed whether
an exception occurs or not. It's optional but often used to release resources like file handles
or network connections.
try {
} catch (Exception e) {
} finally {
// Cleanup code (executed regardless of whether an exception occurred)
import java.io.IOException;
try {
} catch (ArithmeticException e) {
if (b == 0) {
return a / b;
In this example, the divide method throws an ArithmeticException if the divisor is zero. The main
method catches this exception and handles it, preventing the program from crashing.