An exception in Java is an unwanted or unexpected event that occurs during the execution of a program and disrupts the normal flow of instructions.
Java creates an Exception object whenever such an event happens, and throws it to the runtime system.
💡 Real-Life Analogy
Imagine you're booking a movie ticket online.
You:
Select your seat
Proceed to pay
But your internet disconnects during payment
Result: The transaction fails.
➡️ This is similar to an exception in programming — something goes wrong that interrupts the normal flow.
🚨 Error vs Exception
Feature | Error | Exception |
|---|---|---|
Type | Serious issues (like system crash) | Recoverable problems |
Package |
|
|
Handling | Cannot be handled (usually) | Should be handled with code |
Examples |
|
|
📌 Why Do Exceptions Occur?
Dividing a number by zero
Accessing an invalid index in an array
Opening a file that doesn’t exist
Parsing wrong input as number
Using
nullobjects
💥 Common Examples (No Try-Catch Here)
int a = 10 / 0;
// ArithmeticException
String s = null;
System.out.println(s.length());
// NullPointerException
int[] arr = new int[3];
System.out.println(arr[5]);
// ArrayIndexOutOfBoundsException🧠 Why Exception Handling is Needed?
Without proper exception handling:
Your program will crash unexpectedly
The user will see ugly system errors
You cannot control what happens next