Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

Exception Handling in C++: Try, Catch, and Throw

Introduction

Exception handling is a mechanism in C++ to handle runtime errors, ensuring the normal flow of the program is maintained. The keywords try, catch, and throw are used to handle exceptions in C++.

Try Block

A try block is used to wrap the code that might throw an exception. If an exception occurs within the try block, the control is transferred to the appropriate catch block.

Syntax:

try {
    // Code that might throw an exception
}
                

Catch Block

The catch block is used to handle the exception thrown by the try block. The parameter of the catch block is used to identify the type of exception.

Syntax:

catch (exception_type e) {
    // Code to handle the exception
}
                

Throw Statement

The throw statement is used to signal the occurrence of an exception. It can be used to throw objects or fundamental types.

Syntax:

throw exception_object;
                

Example: Division by Zero

Consider a simple example of handling 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 << a / b << endl;
    }
    catch (const char* msg) {
        cerr << "Error: " << msg << endl;
    }
    return 0;
}
                
Output:
Error: Division by zero error

Multiple Catch Blocks

Multiple catch blocks can be used to handle different types of exceptions. The appropriate catch block is executed based on the type of exception thrown.

#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. These exceptions are derived from the std::exception class.

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

int main() {
    try {
        throw runtime_error("Runtime error occurred");
    }
    catch (exception& e) {
        cout << "Standard exception: " << e.what() << endl;
    }
    return 0;
}
                
Output:
Standard exception: Runtime error occurred

Conclusion

Exception handling in C++ using try, catch, and throw is a powerful feature to handle runtime errors gracefully. It ensures that the program can handle unexpected conditions and continue its execution smoothly.