Java Exceptions
⚠️ Java Exceptions – try...catch
An exception is an event that disrupts the normal flow of a program. Exceptions usually occur during runtime — like dividing by zero, accessing invalid array indices, or opening a missing file.
To prevent a program from crashing, we use exception handling with:
🧩 Syntax
✔️ Example 1: Handling Division by Zero
Output:
✔️ Example 2: Catching Multiple Exceptions
You can handle different exceptions separately.
✔️ Example 3: Using a General Exception Catch
Sometimes exact exception type may not be known, so we catch all exceptions:
✔️ Example 4: Try-Catch with finally
finally block runs whether exception occurs or not — useful for closing resources.
🚀 Why Use Try…Catch?
| Without Exception Handling | With Try…Catch |
|---|---|
| Program crashes | Program continues safely |
| No error control | Errors handled gracefully |
| Bad user experience | Better user experience |
🧠 Real-Life Analogy
Try-catch works like:
-
try: “I’ll try opening this jar”
-
catch: “If I can’t, I’ll use a jar opener”
-
finally: “No matter what, I’ll put the jar back in the cupboard.”
Summary:
| Term | Meaning |
|---|---|
| try | Code that may cause an error |
| catch | Handles the error if it happens |
| finally | Executes always |
| Exception | Runtime error |
