Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

Introduction to Exception Handling in C++

What is Exception Handling?

Exception handling is a mechanism in C++ for handling runtime errors, allowing a program to continue operating in a controlled manner. It helps in managing unexpected situations like division by zero, file not found, etc., providing a way to handle these anomalies gracefully.

Basic Concepts

C++ uses three keywords for exception handling:

  • try: The code that might throw an exception is placed inside a try block.
  • catch: This block catches the exceptions thrown by the try block.
  • throw: Used to throw an exception.

Syntax

The basic syntax for exception handling in C++ is as follows:

try {
    // Code that may throw an exception
} catch (ExceptionType e) {
    // Code to handle the exception
}
                

Example

Let's consider a simple example where we divide two numbers and handle the division by zero exception:

#include <iostream>
using namespace std;

int main() {
    int a = 10;
    int b = 0;
    try {
        if (b == 0) {
            throw "Division by zero error!";
        }
        cout << "Result: " << a / b << endl;
    } catch (const char* msg) {
        cerr << "Error: " << msg << endl;
    }
    return 0;
}
                
Output:
Error: Division by zero error!
                

Multiple Catch Blocks

You can have multiple catch blocks to handle different types of exceptions:

#include <iostream>
using namespace std;

int main() {
    try {
        throw 20;
    } catch (int e) {
        cout << "Integer exception caught: " << e << endl;
    } catch (...) {
        cout << "Default exception caught." << endl;
    }
    return 0;
}
                
Output:
Integer exception caught: 20
                

Standard Exceptions

C++ provides a set of standard exceptions defined in the <exception> header file. Some common standard exceptions are:

  • std::exception: Base class for all standard exceptions.
  • std::bad_alloc: Thrown by new on allocation failure.
  • std::out_of_range: Thrown by methods that are passed out-of-range arguments.

Here is an example using a standard exception:

#include <iostream>
#include <exception>
using namespace std;

int main() {
    try {
        throw out_of_range("Out of range exception");
    } catch (const out_of_range& e) {
        cerr << "Caught: " << e.what() << endl;
    } catch (const exception& e) {
        cerr << "Caught: " << e.what() << endl;
    }
    return 0;
}
                
Output:
Caught: Out of range exception
                

Conclusion

Exception handling is a powerful feature in C++ that helps in creating robust and error-resistant programs. By using try, catch, and throw, you can manage runtime errors gracefully, ensuring your program can handle unexpected situations without crashing.