Sobes.tech
Middle

Cu ce se salvează excepțiile în C++?

sobes.tech AI

Răspuns de la AI

Cu obiecte. Când se aruncă o excepție cu throw, se creează un obiect temporar care este apoi transmis mecanismului de tratare a excepțiilor. Tipul acestui obiect determină ce handler catch va fi ales.

Iată un exemplu care demonstrează cum se salvează excepțiile sub formă de obiecte:

#include <iostream>
#include <stdexcept>

class MyException {
    int error_code;
public:
    MyException(int code) : error_code(code) {}
    int get_code() const { return error_code; }
};

void test_func(int val) {
    if (val < 0) {
        // Aruncăm o excepție - obiect al clasei MyException
        throw MyException(-1);
    }
    if (val == 0) {
        // Aruncăm o excepție standard - obiect al clasei std::runtime_error
        throw std::runtime_error("Valoarea nu poate fi zero.");
    }
    std::cout << "Valoarea este pozitivă: " << val << std::endl;
}

int main() {
    try {
        test_func(-5);
    } catch (const MyException& e) {
        // Prindem excepția după tipul obiectului MyException
        std::cerr << "MyException capturată cu codul: " << e.get_code() << std::endl;
    } catch (const std::runtime_error& e) {
        // Prindem excepția după tipul obiectului std::runtime_error
        std::cerr << "std::runtime_error capturat: " << e.what() << std::endl;
    } catch (...) {
        // Prindem orice altă excepție
        std::cerr << "Excepție necunoscută capturată." << std::endl;
    }

    try {
        test_func(0);
    } catch (const std::exception& e) {
        // Se poate prinde clasa de bază pentru excepțiile standard
        std::cerr << "Excepție standard capturată: " << e.what() << std::endl;
    }

    return 0;
}