Exception Handling in C++ with Examples

Exception Handling in C++

Exception handling is a mechanism used to handle runtime errors in a program. Instead of crashing, the program can respond gracefully when an unexpected situation occurs. C++ provides a structured way to detect and manage errors using exception handling.


What is an Exception?

An exception is an abnormal condition that occurs during program execution and disrupts the normal flow of the program.

Examples of Exceptions:

  • Division by zero
  • Accessing invalid memory
  • File not found
  • Array index out of bounds

Why Exception Handling is Important

  • Prevents program crashes
  • Improves program reliability
  • Separates error-handling code
  • Makes debugging easier
  • Enhances user experience

Keywords Used in Exception Handling

C++ uses three main keywords:

  • try
  • catch
  • throw

try Block

The try block contains code that may generate an exception.

try {
    // risky code
}

catch Block

The catch block handles the exception thrown in the try block.

catch(int e) {
    // handle exception
}

Multiple catch blocks can be used to handle different exceptions.


throw Keyword

The throw keyword is used to explicitly throw an exception.

throw value;

Example of Exception Handling

int a = 10, b = 0;
try {
    if(b == 0)
        throw b;
    cout << a / b;
}
catch(int x) {
    cout << "Division by zero error";
}

Multiple Catch Blocks

Allows handling different types of exceptions.

catch(int e) { }
catch(char e) { }
catch(...) { }

The catch(...) block catches all exceptions.


Exception Handling with Functions

Exceptions can be thrown from functions and caught in the calling function.

This improves modularity and clean error handling.


Standard Exceptions in C++

C++ provides built-in exception classes like:

  • bad_alloc
  • out_of_range
  • runtime_error
  • logic_error

Defined in <exception> and <stdexcept>.


Advantages of Exception Handling

  • Clean error-handling code
  • Maintains program flow
  • Improves code readability
  • Enhances application stability

Real-World Example

Example: Banking System

  • Insufficient balance
  • Invalid account number

Exception handling ensures the system doesn’t crash and displays proper error messages.


Common Mistakes to Avoid

  • Catching exceptions by value
  • Ignoring exceptions
  • Overusing catch-all handlers
  • Throwing primitive types excessively

Conclusion

Exception handling allows C++ programs to handle runtime errors gracefully using try, catch, and throw. It improves program robustness and reliability, making it an essential concept for real-world software development.

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *