codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Subjects
🧩

OOP Concepts

23 chapters

1Procedural vs Object-Oriented2Classes, Objects, & Instantiation3Constructors & Destructors4Static Members & Methods5Encapsulation & Access Modifiers6Data Abstraction7Inheritance Types (Single, Multiple)8Compile-Time Polymorphism (Overloading)9Polymorphism & Interfaces10Run-Time Polymorphism (Overriding)11Virtual Functions & V-Tables12Interfaces & Abstract Classes13Generic Programming (Templates & Generics)14Exception Handling in OOP15SOLID Design Principles16Composition over Inheritance17Coupling & Cohesion18UML Diagrams Basics19Creational Patterns (Singleton, Factory)20Structural Patterns (Adapter, Decorator)21Behavioral Patterns (Observer, Strategy)22MVC Architecture Pattern23Object Serialization & Cloning
SubjectsOOP Concepts

Exception Handling in OOP

Updated 2026-04-21
1 min read

Exception Handling in OOP

Exception Handling is a mechanism to handle runtime errors (file not found, division by zero, null pointer access) gracefully, without crashing the entire program. It separates error-handling code from normal business logic.

1. The try-catch-finally Pattern

try {
    // Code that might throw an exception
    int result = 10 / 0;
} catch (ArithmeticException e) {
    // Handle the specific exception
    System.out.println("Cannot divide by zero: " + e.getMessage());
} catch (Exception e) {
    // Catch-all for any other exception
    System.out.println("Unexpected error: " + e.getMessage());
} finally {
    // ALWAYS executes, whether exception occurred or not
    // Used for cleanup: closing files, database connections, etc.
    System.out.println("Cleanup complete.");
}

2. Exception Hierarchy

In Java, all exceptions inherit from Throwable:

  • Error: Serious problems the application should NOT try to handle (OutOfMemoryError, StackOverflowError).
  • Exception:
    • Checked Exceptions: Must be explicitly caught or declared with throws. Compile-time enforcement. Examples: IOException, SQLException.
    • Unchecked Exceptions (RuntimeException): Do not need to be declared. Examples: NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException.

3. Custom Exceptions

class InsufficientFundsException extends Exception {
    private double amount;
    public InsufficientFundsException(double amount) {
        super("Insufficient funds. Short by: $" + amount);
        this.amount = amount;
    }
    public double getAmount() { return amount; }
}

// Usage
void withdraw(double amount) throws InsufficientFundsException {
    if (amount > balance)
        throw new InsufficientFundsException(amount - balance);
    balance -= amount;
}

4. Best Practices

  • Catch specific exceptions first, then general ones. Catching Exception too broadly hides bugs.
  • Never swallow exceptions (empty catch blocks). At minimum, log the error.
  • Use finally for cleanup, or better, use try-with-resources (Java) / RAII (C++) for automatic resource management.
  • Throw early, catch late. Throw exceptions as close to the source of the error as possible. Catch them at a level where you can meaningfully handle them.
  • Don't use exceptions for control flow. Exceptions are for exceptional situations, not for normal program logic.


PreviousGeneric Programming (Templates & Generics)NextSOLID Design Principles

Recommended Gear

Generic Programming (Templates & Generics)SOLID Design Principles