Exception Handling in Java
1. What Is an Exception?
An exception in Java is an abnormal event that occurs during program execution and disrupts the
normal flow of instructions. It represents runtime errors such as:
Dividing by zero
Accessing invalid array index
Opening a non-existent file
Invalid user input
Network failures
Java provides a built-in mechanism to detect, report, and handle such errors — called exception
handling.
2. Why Exception Handling Is Important
Exception handling helps to:
Prevent program crashes
Maintain normal program flow
Separate error handling code from regular logic
Provide meaningful error messages
Improve software reliability
Support graceful recovery
Without exception handling, a runtime error stops the program immediately.
3. Types of Errors in Java
Java problems are generally grouped into:
✅a) Compile-Time Errors
Detected by the compiler.
Examples:
Missing semicolon
Undeclared variable
Type mismatch
✅b) Runtime Errors (Exceptions)
Occur during program execution.
Examples:
Divide by zero
File not found
Null reference access
✅c) Logical Errors
Program runs but gives wrong output.
Example:
average = sum / count + 1 // wrong logic
4. What Is an Exception Object?
In Java, an exception is an object created when an error occurs.
When an exception occurs:
1. Exception object is created
2. It is thrown
3. Runtime system searches for a handler
4. If found → handled
5. If not → program terminates
5. Exception Class Hierarchy
All exceptions inherit from:
Object
└── Throwable
├── Error
└── Exception
├── Checked Exceptions
└── Unchecked Exceptions
6. Types of Exceptions
✅A) Checked Exceptions
Checked at compile time
Must be handled or declared
Compiler forces handling
Examples:
IOException
SQLException
FileNotFoundException
ClassNotFoundException
Example:
FileReader f = new FileReader("[Link]"); // must handle
✅B) Unchecked Exceptions
Occur at runtime
Not checked at compile time
Usually caused by programming errors
Examples:
ArithmeticException
NullPointerException
ArrayIndexOutOfBoundsException
IllegalArgumentException
Example:
int x = 10 / 0; // ArithmeticException
✅C) Errors
Serious system problems
Not meant to be handled by programs
Examples:
OutOfMemoryError
StackOverflowError
7. Java Exception Handling Keywords
Java provides five main keywords:
Keyword Purpose
try Block that may throw exception
catch Handles exception
Keyword Purpose
finally Always executes
throw Manually throw exception
throws Declares possible exceptions
8. Try–catch Block
Used to catch and handle exceptions.
Syntax
try {
// risky code
} catch (ExceptionType e) {
// handling code
}
Example
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
[Link]("Cannot divide by zero");
}
9. Multiple catch Blocks
You can handle different exceptions separately.
try {
int arr[] = new int[5];
arr[10] = 50;
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Index error");
} catch (Exception e) {
[Link]("General error");
}
Order matters — specific exceptions must come before general ones.
10. finally Block
The finally block always executes whether an exception occurs or not.
Used for:
Closing files
Releasing resources
Closing database connections
try {
int x = 5;
} catch (Exception e) {
[Link]("Error");
} finally {
[Link]("Always runs");
}
11. try-with-resources (Automatic Resource Management)
Automatically closes resources.
try (FileReader f = new FileReader("[Link]")) {
// use file
} catch (IOException e) {
[Link]("File error");
}
Resources must implement AutoCloseable.
12. throw Keyword
Used to manually throw an exception.
throw new ArithmeticException("Invalid division");
Example:
int age = -5;
if (age < 0) {
throw new IllegalArgumentException("Age cannot be
negative");
}
13. throws Keyword
Declares exceptions that a method may throw.
public void readFile() throws IOException {
FileReader f = new FileReader("[Link]");
}
It shifts responsibility to the caller.
14. Difference: throw vs throws
throw throws
Used inside method Used in method signature
Throws single exception Can declare multiple
Creates exception object Declares possibility
15. Nested try Blocks
A try block inside another try block.
try {
try {
int x = 10 / 0;
} catch (ArithmeticException e) {
[Link]("Inner catch");
}
} catch (Exception e) {
[Link]("Outer catch");
}
16. Custom Exceptions (User-Defined)
You can create your own exception classes.
Step 1: Extend Exception
class InvalidAgeException extends Exception {
public InvalidAgeException(String msg) {
super(msg);
}
}
Step 2: Use It
if (age < 18) {
throw new InvalidAgeException("Not eligible");
}
17. Common Built-in Exceptions
ArithmeticException
int x = 5/0;
NullPointerException
String s = null;
[Link]();
ArrayIndexOutOfBoundsException
arr[10];
NumberFormatException
[Link]("abc");
18. Exception Propagation
If not handled, exceptions move up the call stack.
method3() → method2() → method1() → main()
If none handles → program terminates.
19. Best Practices
Catch specific exceptions
Don’t use empty catch blocks
Use finally or try-with-resources
Provide meaningful messages
Don’t overuse exceptions for normal logic
Log exceptions properly
Clean up resources
20. Example — Complete Program
public class Demo {
public static void main(String[] args) {
try {
int a = 20;
int b = 0;
int c = a / b;
} catch (ArithmeticException e) {
[Link]("Division by zero not allowed");
} finally {
[Link]("Program continues");
}
}
}