Exception Handling
Exception Handling
Exception handling in Java allows developers to manage runtime errors, ensuring that the normal flow of a program is maintained
even when errors occur. Without exception handling, errors would cause abrupt termination of the program, which is undesirable
in most applications. Exception handling provides a robust mechanism for managing errors, allowing developers to deal with
unexpected conditions effectively.
What is an Exception?
An exception is an event that occurs during the execution of a program and disrupts its normal flow. In Java, exceptions are objects
that encapsulate error information. Exceptions occur due to several reasons:
Exceptions in Java are objects, and they are derived from the java.lang.Throwable class. The Throwable class has two
main subclasses:
1. Error: Represents serious system-level errors that typically cannot be handled by the program (e.g.,
OutOfMemoryError, StackOverflowError). Errors indicate problems that the application should not try to
catch.
2. Exception: Represents conditions that applications might want to catch and handle. Exception is further divided into:
o Checked Exceptions: Exceptions that the compiler requires to be handled or declared using throws (e.g.,
IOException, SQLException).
o Unchecked Exceptions: Also known as runtime exceptions. These are not checked at compile time, and occur
due to programming errors like logic mistakes (e.g., NullPointerException,
ArrayIndexOutOfBoundsException, ArithmeticException).
java.lang.Throwable
├── java.lang.Error
└── java.lang.Exception
├── java.lang.RuntimeException
└── other exceptions (Checked Exceptions)
Types of Exceptions
1. Checked Exceptions: These are exceptions that a programmer must handle in the code. If a checked exception is not
caught or declared in the method signature, the program will not compile. These are typically external issues, such as file
handling errors or network problems.
o Examples: IOException, SQLException, FileNotFoundException.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
1. try: The code that might throw an exception is placed inside the try block.
2. catch: The code that handles the exception is placed inside the catch block.
3. finally: A block of code that always executes, whether an exception is thrown or not. It is typically used for resource
cleanup (e.g., closing file or database connections).
4. throw: Used to explicitly throw an exception.
5. throws: Used to declare that a method might throw an exception. This is required for checked exceptions that the method
does not handle.
The finally block always executes, regardless of whether an exception is thrown or not. It is often used to close resources like
files, network connections, or databases.
• In this example, the finally block will execute even though no exception occurs.
The throw keyword is used to explicitly throw an exception. This is useful for throwing custom exceptions.
• The checkEligibility method throws an ArithmeticException if the age is less than 18.
The throws keyword is used to declare that a method might throw an exception but does not handle it.
import java.io.IOException;
• The validateFile method throws an IOException which is not handled but declared using the throws
keyword.
Custom Exceptions
Java allows developers to create their own exceptions by extending the Exception class.
• InvalidAgeException is a custom exception that is thrown if the age is less than 18.
Exception Propagation
When an exception is thrown, it is propagated up the call stack until it is caught by an appropriate catch block.
void method2() {
method1(); // Exception propagates to this method
}
• The exception occurs in method1() and is propagated to method2() and then to the main() method, where it is
caught.
1. Use specific exceptions: Always catch specific exceptions, rather than using a general Exception block.
2. Clean up resources in finally: Use the finally block to release resources, such as closing files, network connections,
or database connections.
3. Don’t ignore exceptions: Avoid using empty catch blocks; always handle exceptions meaningfully.
4. Don’t use exceptions for flow control: Exceptions should be used for handling exceptional conditions, not for normal
program flow.
5. Throw custom exceptions: Create meaningful custom exceptions that convey the cause of the error clearly.