🔹 Exception Handling in OOP

**Exception Handling** is a mechanism in Object-Oriented Programming (OOP) that allows a program to **handle runtime errors** gracefully, preventing crashes and ensuring smooth execution.

📌 Why Use Exception Handling?

Exception handling ensures that programs **fail safely** and provide meaningful error messages.

  • ✅ **Prevents Program Crashes** – Handles errors gracefully.
  • ✅ **Improves Debugging** – Provides clear error messages.
  • ✅ **Enhances User Experience** – Ensures smooth program execution.
  • ✅ **Encapsulates Error Handling** – Keeps business logic separate from error handling.

📌 Exception Handling Keywords

Most OOP languages use the following **keywords**:

  • try – Defines a block where exceptions may occur.
  • catch – Handles specific exceptions.
  • finally – Executes code regardless of whether an exception occurred.
  • throw – Manually throws an exception.
  • throws – Declares exceptions a method may throw.

🖥️ Example: Exception Handling in Java


            public class ExceptionExample {
                public static void main(String[] args) {
                    try {
                        int result = 10 / 0;  // ❌ Division by zero error
                    } catch (ArithmeticException e) {
                        System.out.println("Error: Cannot divide by zero.");
                    } finally {
                        System.out.println("Execution completed.");
                    }
                }
            }
                

🖥️ Example: Exception Handling in Python


            try:
                result = 10 / 0  # ❌ Division by zero
            except ZeroDivisionError:
                print("Error: Cannot divide by zero.")
            finally:
                print("Execution completed.")
                

📌 Custom Exceptions

We can define **custom exceptions** for better error handling.

🖥️ Custom Exception in Java


            class InvalidAgeException extends Exception {
                public InvalidAgeException(String message) {
                    super(message);
                }
            }
            
            public class Main {
                public static void checkAge(int age) throws InvalidAgeException {
                    if (age < 18) {
                        throw new InvalidAgeException("Age must be 18 or above.");
                    }
                }
            
                public static void main(String[] args) {
                    try {
                        checkAge(16);
                    } catch (InvalidAgeException e) {
                        System.out.println(e.getMessage());
                    }
                }
            }
                

🖥️ Custom Exception in Python


            class InvalidAgeException(Exception):
                def __init__(self, message):
                    self.message = message
                    super().__init__(self.message)
            
            def check_age(age):
                if age < 18:
                    raise InvalidAgeException("Age must be 18 or above.")
            
            try:
                check_age(16)
            except InvalidAgeException as e:
                print(e)
                

🎯 Summary

Exception Handling ensures **error-free program execution** by using **try, catch, finally, throw, and custom exceptions**. It improves **code reliability, debugging, and user experience**.

🔗 Next Topics