What is an Exception in Java?
An exception in Java is an unexpected event that occurs during the execution of a program and interrupts the normal flow of instructions. It is not a compile-time error, it happens at runtime.
Simple Definition
An exception is a runtime problem that stops program execution unless handled properly.
Why Exceptions Occur?
Exceptions occur due to invalid operations, such as:
- Dividing a number by zero
- Accessing an array index out of range
- Opening a file that doesn’t exist
- Passing null where an object is required
- Type conversion errors
- Network or database failure
Example: Without Exception Handling
public class Example {
public static void main(String[] args) {
int a = 10;
int b = 0;
int result = a / b; // Exception occurs here
System.out.println(result);
}
}
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
Program crashes and stops executing.
How Java Handles Exceptions?
When an exception occurs:
- Java creates an Exception object
- Passes (throws) it to the JVM
- JVM looks for a matching catch block
- If not found → program terminates abnormally
Exception vs Error
| Feature | Exception | Error |
|---|---|---|
| Type | Recoverable | Non-recoverable |
| Examples | ArithmeticException, NullPointerException | OutOfMemoryError, StackOverflowError |
| Programmer Can Handle? | YES | NO |
| Package | java.lang.Exception | java.lang.Error |
Exception Hierarchy
Throwable
│
├── Exception → can be handled
│ ├── RuntimeException
│ └── IOException, SQLException etc.
│
└── Error → cannot be handled
Real-Life Analogy
If your laptop suddenly shuts down while working → this interruption is similar to a Java exception.
If your laptop’s motherboard burns → it’s like a Java Error → cannot be handled.
Why Exception Handling is Needed?
- Prevents program crashes
- Displays meaningful error messages
- Allows graceful program recovery
- Helps debugging
- Makes applications more stable & user-friendly
