Java Docs
Java Documentation
Java Exceptions
An exception is an unexpected event that occurs during program execution. It disrupts the normal flow of instructions and can cause programs to terminate abnormally.
Common causes of exceptions include:
- Invalid user input
- Device failure
- Loss of network connection
- Out of disk memory
- Programming errors
- Opening a file that does not exist
Java Exception Hierarchy
The root of the exception hierarchy is the Throwable class. The hierarchy splits into two main branches:
- Error – irrecoverable issues (e.g., JVM running out of memory).
- Exception – can be caught and handled.
Exceptions
When an exception occurs, Java creates an exception object containing details such as its name, description, and the program state at the moment it occurred.
There are two major categories of exceptions:
1. RuntimeException (Unchecked)
Runtime exceptions occur due to programmer mistakes. These are not checked by the compiler.
IllegalArgumentException– improper API useNullPointerException– accessing null objectsArrayIndexOutOfBoundsException– invalid array indexArithmeticException– dividing by zero
A common way to remember:
If it is a runtime exception, it is your fault.
2. IOException (Checked)
Checked exceptions are verified by the compiler. The programmer is required to handle them.
FileNotFoundException– file does not exist- Attempting to read beyond the end of a file
Example: Basic Exception Demonstration
class Main {
public static void main(String[] args) {
try {
int a = 10 / 0; // triggers ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Exception occurred: " + e.getMessage());
}
System.out.println("Program continues...");
}
}Output
Exception occurred: / by zero Program continues...
Now that you understand exceptions, the next step is learning how to handle them using try-catch, finally, and throw/throws.