🌼 Java Exception Handling — Complete Lesson (Programmer’s Picnic)

🌼 Java Exception Handling — Complete Lesson (Programmer’s Picnic)

Exception Handling allows your Java program to avoid crashing and instead handle errors gracefully with meaningful messages. This is one of the most important topics for interviews and real-world development.

1️⃣ What is an Exception?

An Exception is an unwanted event that occurs during the execution of a program and disrupts the normal flow of instructions.

✔ Types of Exceptions

  • Checked Exceptions — Verified at compile time (IOException, SQLException)
  • Unchecked Exceptions — Occur at runtime (NullPointerException, ArithmeticException)
  • Errors — Serious issues, not handled usually (OutOfMemoryError)
Think of exception handling like keeping a spare tire in your car — Even if a problem occurs, the journey continues.

2️⃣ Why Do We Need Exception Handling?

  • Prevents program crash
  • Provides user-friendly messages
  • Makes debugging easier
  • Keeps application stable

3️⃣ Exception Handling Keywords

KeywordPurpose
tryCode that may throw an exception
catchHandles the exception
finallyRuns always (cleanup)
throwManually throw an exception
throwsSend exception to method caller

4️⃣ Basic try–catch Example

public class Example1 { public static void main(String[] args) { try { int a = 10 / 0; // ArithmeticException } catch (ArithmeticException e) { System.out.println("Cannot divide by zero!"); } } }

5️⃣ Multiple Catch Blocks

try { String s = null; System.out.println(s.length()); } catch (ArithmeticException e) { System.out.println("Math issue!"); } catch (NullPointerException e) { System.out.println("Null value found!"); } catch (Exception e) { System.out.println("General exception: " + e); }

Rule: Keep Exception catch block at the end.

6️⃣ finally Block

try { int arr[] = {1,2,3}; System.out.println(arr[5]); } catch (Exception e) { System.out.println("Error: " + e); } finally { System.out.println("This will always run!"); }

7️⃣ The throw Keyword

public void checkAge(int age) { if(age < 18) { throw new ArithmeticException("Not eligible!"); } System.out.println("You can vote!"); }

8️⃣ The throws Keyword

public void readFile() throws IOException { FileReader fr = new FileReader("data.txt"); }

9️⃣ Creating Custom Exceptions

class LowBalanceException extends Exception { public LowBalanceException(String msg) { super(msg); } } class Bank { void withdraw(int balance, int amount) throws LowBalanceException { if(amount > balance) throw new LowBalanceException("Balance too low!"); System.out.println("Withdraw successful!"); } }

🔟 try-with-resources (Java 7+)

try (FileReader fr = new FileReader("data.txt")) { // Reading code } catch (IOException e) { System.out.println(e); }

1️⃣1️⃣ Exception Hierarchy (Simple)

Throwable
   ├── Exception
   │       └── RuntimeException
   │             ├── ArithmeticException
   │             ├── NullPointerException
   └── Error
         └── OutOfMemoryError

1️⃣2️⃣ MCQs (With Answers)

  1. Which keyword is used for exception handling? Answer: All of the above (try, catch, throw, throws)
  2. Which is an unchecked exception? NullPointerException
  3. finally block executes: Always
  4. Parent of all exceptions? Throwable
  5. If no catch matches, program: Crashes
  6. Keyword to manually generate exception: throw
  7. Keyword to delegate exception: throws
  8. Custom exception extends: Exception
  9. try-with-resources introduced in: Java 7
  10. 10 / 0 gives: ArithmeticException

1️⃣3️⃣ Assignments (Beginner to Advanced)

🟡 Assignment 1 (Easy)

Create a program to divide two numbers. Handle ArithmeticException if user enters zero.

🟠 Assignment 2 (Moderate)

Take a string input and print length. Handle NullPointerException.

🟠 Assignment 3 (Moderate)

Simulate login: Throw new Exception("Invalid Username") if username ≠ admin.

🔵 Assignment 4 (Advanced)

Create AgeTooSmallException. Trigger it if age < 10. Use both throw and throws.

🔵 Assignment 5 (Advanced)

Bank withdrawal simulation using custom exception.

🔴 Assignment 6 (Expert)

Read a file using:
  • try-with-resources
  • throws declaration
  • Multiple catch blocks (IO, FileNotFound)
✨ Keep learning! Save this page and practice each assignment to master Java Exception Handling. Your consistency is your superpower. 💛 — Programmer’s Picnic

0 Comments

Post a Comment

0 Comments

⬅ Go Home