Sobes.tech
Middle

C++'ta istisnalar nasıl saklanır?

sobes.tech yapay zeka

AI'dan gelen yanıt

Nesnelerle. throw kullanılarak bir istisna atıldığında, geçici bir nesne oluşturulur ve bu nesne istisna işleme mekanizmasına iletilir. Bu nesnenin tipi, hangi catch işleyicisinin seçileceğini belirler.

İşte nesne biçiminde istisnaların nasıl saklanacağını gösteren bir örnek:

#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) {
        // İstisna atıyoruz - MyException sınıfı nesnesi
        throw MyException(-1);
    }
    if (val == 0) {
        // Standart istisna atıyoruz - std::runtime_error sınıfı nesnesi
        throw std::runtime_error("Değer sıfır olamaz.");
    }
    std::cout << "Değer pozitif: " << val << std::endl;
}

int main() {
    try {
        test_func(-5);
    } catch (const MyException& e) {
        // MyException türündeki istisnayı yakalıyoruz
        std::cerr << "MyException yakalandı, kod: " << e.get_code() << std::endl;
    } catch (const std::runtime_error& e) {
        // std::runtime_error türündeki istisnayı yakalıyoruz
        std::cerr << "std::runtime_error yakalandı: " << e.what() << std::endl;
    } catch (...) {
        // Herhangi başka bir istisnayı yakalıyoruz
        std::cerr << "Bilinmeyen istisna yakalandı." << std::endl;
    }

    try {
        test_func(0);
    } catch (const std::exception& e) {
        // Standart istisnalar için temel sınıf yakalanabilir
        std::cerr << "Standart istisna yakalandı: " << e.what() << std::endl;
    }

    return 0;
}