Exception Handling
In real-world applications, things do not always go as planned. Files may be missing, user input may be wrong, or systems may fail.
Exception Handling in Java helps your program handle such situations gracefully instead of crashing.
What Is an Exception?
An exception is an unexpected event that occurs during program execution and disrupts the normal flow of the program.
Examples include:
- Dividing a number by zero
- Accessing an invalid array index
- Opening a file that does not exist
- Invalid user input
Why Exception Handling Is Important
Without exception handling, a single error can terminate an entire application.
With proper exception handling, you can:
- Prevent application crashes
- Display meaningful error messages
- Maintain system stability
- Recover from errors where possible
Basic Example Without Exception Handling
This program crashes when an error occurs.
public class Main {
public static void main(String[] args) {
int a = 10;
int b = 0;
System.out.println(a / b);
}
}
This results in a runtime error.
Using try and catch
Java uses try and catch blocks to handle exceptions.
public class Main {
public static void main(String[] args) {
try {
int a = 10;
int b = 0;
System.out.println(a / b);
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
}
}
}
The program no longer crashes and continues execution safely.
Multiple catch Blocks
You can handle different types of exceptions separately.
try {
int[] numbers = {1, 2, 3};
System.out.println(numbers[5]);
} catch (ArithmeticException e) {
System.out.println("Math error");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Invalid index accessed");
}
Using finally Block
The finally block always executes,
whether an exception occurs or not.
try {
System.out.println("Inside try block");
} catch (Exception e) {
System.out.println("Exception caught");
} finally {
System.out.println("Cleanup completed");
}
This is commonly used for closing resources.
Real-World Example
Consider handling user input in a banking application.
int balance = 5000;
int withdrawAmount = 7000;
try {
if (withdrawAmount > balance) {
throw new IllegalArgumentException("Insufficient balance");
}
balance -= withdrawAmount;
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
Checked vs Unchecked Exceptions
- Checked Exceptions – checked at compile time (IOException)
- Unchecked Exceptions – occur at runtime (NullPointerException)
Java forces developers to handle checked exceptions explicitly.
Common Exception Classes
- ArithmeticException
- NullPointerException
- ArrayIndexOutOfBoundsException
- IllegalArgumentException
Best Practices
- Handle exceptions at the correct level
- Do not hide errors silently
- Use meaningful error messages
- Avoid generic catch blocks when possible
Key Takeaways
- Exception handling prevents application crashes
- try–catch–finally ensures safe execution
- Essential for production-grade Java code
In the next lesson, we will explore Multithreading and how Java executes tasks concurrently.