What is an Exception in Java?
An exception is an event that disrupts the normal flow of the program during execution. It occurs when something goes wrong — for example, dividing by zero or accessing an invalid array index.
Java handles exceptions using a powerful mechanism that helps avoid program crashes and manage errors gracefully.
Exception Hierarchy
Object
└── Throwable
├── Error (serious issues, ignored usually)
└── Exception (handled by the program)
├── Checked Exception (must handle)
└── Unchecked Exception (runtime, optional handling)
Types of Exceptions
1. Checked Exceptions
Handled at compile-time (e.g., IOException
, SQLException
)
2. Unchecked Exceptions
Handled at runtime (e.g., ArithmeticException
, NullPointerException
)
Basic Exception Handling Syntax
try {
// Code that may throw an exception
} catch (ExceptionType name) {
// Code to handle the exception
} finally {
// Code that will always execute (optional)
}
Example 1: Divide by Zero (Unchecked Exception)
public class ExceptionExample {
public static void main(String[] args) {
try {
int a = 10;
int b = 0;
int c = a / b; // This will throw ArithmeticException
System.out.println("Result: " + c);
} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero!");
} finally {
System.out.println("Finally block always runs.");
}
}
}
Output:
Error: Cannot divide by zero!
Finally block always runs.
Example 2: File Handling (Checked Exception)
import java.io.*;
public class FileExample {
public static void main(String[] args) {
try {
FileReader file = new FileReader("data.txt");
BufferedReader reader = new BufferedReader(file);
System.out.println(reader.readLine());
reader.close();
} catch (IOException e) {
System.out.println("File not found or error reading file: " + e.getMessage());
}
}
}
Note: You must handle
IOException
, or the compiler will throw an error.
Keywords Summary
Keyword | Use |
---|---|
try |
Block of code to monitor for exceptions |
catch |
Block to handle the exception |
finally |
Always executes (used for cleanup like closing files) |
throw |
Manually throw an exception |
throws |
Declares exception that a method might throw |
Custom Exception Example
You can even create your own exception class:
class MyException extends Exception {
MyException(String msg) {
super(msg);
}
}
public class CustomEx {
static void validateAge(int age) throws MyException {
if (age < 18)
throw new MyException("You must be 18+ to register.");
else
System.out.println("Valid age for registration.");
}
public static void main(String[] args) {
try {
validateAge(16);
} catch (MyException e) {
System.out.println("Caught custom exception: " + e.getMessage());
}
}
}
Output:
Caught custom exception: You must be 18+ to register.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Terms Disclaimer About Us Contact Us
Copyright 2023-2025 © All rights reserved.