■ Exception Handling in Java
1. Introduction
An exception is an unexpected event that occurs during the execution of a program and disrupts its
normal flow. Exception Handling is the mechanism to handle runtime errors so that the program
continues execution without crashing.
2. Keywords in Exception Handling
try - The block of code where exceptions might occur.
catch - Handles the exception generated inside try.
throw - Used to manually throw an exception.
throws - Declares the exceptions that a method may throw.
finally - Always executes (whether exception occurs or not). Used for cleanup.
3. Types of Exceptions
(a) Checked Exceptions – Known at compile-time. Must be handled with try-catch or declared
using throws. Examples: IOException, SQLException.
(b) Unchecked Exceptions – Known at runtime. Occur due to logical mistakes. Examples:
ArithmeticException, NullPointerException.
(c) Errors – Serious issues, not meant to be handled. Examples: OutOfMemoryError,
StackOverflowError.
4. Common Built-in Exceptions
Exception Class When it occurs
ArithmeticException Dividing by zero
NullPointerException Using an object reference that is null
ArrayIndexOutOfBoundsException Accessing array with illegal index
NumberFormatException Converting invalid string to number
IOException Input-output operation failure
FileNotFoundException File not available
5. Creating Own Exception Class (User-defined Exceptions)
We can create custom exceptions by extending Exception (checked) or RuntimeException
(unchecked).
Example:
class AgeException extends Exception {
public AgeException(String message) { super(message); }
}
public class Test {
public static void main(String[] args) {
try {
int age = 15;
if (age < 18) {
throw new AgeException("Age must be 18 or above");
}
} catch (AgeException e) {
System.out.println("Exception caught: " + e.getMessage());
}
}
}
6. Garbage Collection
Java has an automatic Garbage Collector (GC) to free memory by destroying unused objects. We
can request GC using:
System.gc();
7. finalize() Method
The finalize() method is called by GC before destroying an object. It can be overridden for cleanup.
Example:
class Test {
protected void finalize() {
System.out.println("Object is garbage collected");
}
public static void main(String[] args) {
Test obj = new Test();
obj = null;
System.gc();
}
}
8. Flow of Exception Handling
1. Code runs inside try block.
2. If exception occurs → catch executes.
3. If no exception → catch skipped.
4. finally always executes.