C++ Exception Handling Tutorial

Exception handling in C++ provides a mechanism to detect and manage runtime errors, ensuring program stability and reliability. It uses the `try`, `catch`, and `throw` keywords to handle exceptions gracefully.

Basic Syntax

Exception handling in C++ involves three main components:

  • try: Defines a block of code that might throw an exception.
  • catch: Handles the exception thrown by the `try` block.
  • throw: Throws an exception to be caught.

#include <iostream>
using namespace std;

int main() {
    try {
        throw "An error occurred!";
    } catch (const char* msg) {
        cout << "Caught exception: " << msg << endl;
    }
    return 0;
}
                

Handling Multiple Exceptions

Multiple `catch` blocks can handle different exception types:


#include <iostream>
using namespace std;

int main() {
    try {
        throw 404;
    } catch (int e) {
        cout << "Caught integer exception: " << e << endl;
    } catch (...) {
        cout << "Caught unknown exception!" << endl;
    }
    return 0;
}
                

Custom Exception Classes

You can create your own exception classes to handle specific scenarios:


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

class CustomException : public exception {
public:
    const char* what() const noexcept override {
        return "Custom exception occurred!";
    }
};

int main() {
    try {
        throw CustomException();
    } catch (const CustomException& e) {
        cout << e.what() << endl;
    }
    return 0;
}
                

Best Practices

  • Use exceptions for exceptional conditions, not for regular control flow.
  • Catch exceptions by reference to avoid unnecessary copying.
  • Always clean up resources using RAII or `try-finally` mechanisms.
0 Interaction
1.5K Views
Views
25 Likes
×
×
🍪 CookieConsent@Ptutorials:~

Welcome to Ptutorials

Note: We aim to make learning easier by sharing top-quality tutorials.

We kindly ask that you refrain from posting interactions unrelated to web development, such as political, sports, or other non-web-related content. Please be respectful and interact with other members in a friendly manner. By participating in discussions and providing valuable answers, you can earn points and level up your profile.

$ Allow cookies on this site ? (y/n)

top-home