checked and unchecked exceptions
✅ 1. Checked Exceptions (Compile-Time Exceptions)
These are exceptions that the Java compiler forces you to handle. If your code might throw a checked exception, you must either:
-
Handle it using a
try-catchblock, or -
Declare it using the
throwskeyword in the method signature
📌 Common Checked Exceptions:
-
IOException -
FileNotFoundException -
SQLException -
ClassNotFoundException
📘 Example – File Handling:
🔍 What Happens?
-
If you remove the
try-catch, the compiler gives an error: unreported exception must be caught or declared to be thrown.
✅ 2. Unchecked Exceptions (Runtime Exceptions)
These are exceptions derived from RuntimeException. Java does not require you to catch or declare them. They usually represent programming bugs like invalid logic or null references.
📌 Common Unchecked Exceptions:
-
NullPointerException -
ArithmeticException -
ArrayIndexOutOfBoundsException -
IllegalArgumentException
📘 Example – Divide by Zero:
🔍 What Happens?
-
The code compiles without error.
-
But at runtime, it crashes with:
Exception in thread "main" java.lang.ArithmeticException: / by zero
🔄 Key Differences Summary:
Feature Checked Exception Unchecked Exception Checked at Compile-Time? ✅ Yes ❌ No Must be handled? ✅ Yes (try-catch or throws) ❌ No (optional) Inherits from Exception RuntimeExceptionExamples IOException, SQLException NullPointerException, ArithmeticExceptionCommon use External errors (I/O, DB) Code bugs (nulls, logic)
| Feature | Checked Exception | Unchecked Exception |
|---|---|---|
| Checked at Compile-Time? | ✅ Yes | ❌ No |
| Must be handled? | ✅ Yes (try-catch or throws) | ❌ No (optional) |
| Inherits from | Exception | RuntimeException |
| Examples | IOException, SQLException | NullPointerException, ArithmeticException |
| Common use | External errors (I/O, DB) | Code bugs (nulls, logic) |
💡 Best Practice
-
Handle checked exceptions properly with meaningful messages.
-
Avoid unchecked exceptions by writing safe code (e.g., check for nulls, bounds).
Comments
Post a Comment