💥 What is an Exception?
An exception is a problem that occurs during the execution of a program. When
this happens, the program stops working normally and may crash unless we
handle the error properly.
🧠 Think of it like this:
Imagine you're withdrawing money from an ATM. If you enter the wrong PIN,
the transaction fails — but the machine doesn’t crash! It shows you a message
and lets you try again. That’s like exception handling.
🛡️Why Do We Need Exception Handling?
Prevents the program from crashing.
Helps in debugging (error messages show what went wrong).
Makes the program more robust and user-friendly.
🔍 Types of Exceptions in Java
✅ Checked Exceptions
Java forces you to handle these.
They are checked at compile-time.
Examples: IOException, SQLException, FileNotFoundException.
📌 Example:
java
CopyEdit
, FileReader file = new FileReader("file.txt"); // may throw
FileNotFoundException
You must handle it using try-catch or throws.
❌ Unchecked Exceptions
Optional to handle.
They happen at runtime.
Examples: ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException.
📌 Example:
java
CopyEdit
int a = ; // ArithmeticException
🧵 Java Exception Class Hierarchy
php
CopyEdit
Throwable
├── Error (not recoverable, e.g., memory crash)
└── Exception
├── Checked Exceptions
└── RuntimeException (Unchecked)
⚙️
How Exception Handling Works (with Syntax)
Basic Structure:
java
CopyEdit
try {
// code that may throw exception
} catch (ExceptionType e) {
// code to handle the exception
} finally {
// code that always runs (optional)