Sobes.tech
Middle

C++ da istisnolar qanday saqlanadi?

sobes.tech AI

AIdan javob

Ob'ektlar bilan. throw yordamida istisno tashlashda, vaqtinchalik ob'ekt yaratiladi va keyin istisno bilan ishlash mexanizmi orqali uzatiladi. Bu ob'ektning turi qaysi catch tutuvchisi tanlanishini belgilaydi.

Mana, ob'ekt shaklida istisnolarni saqlashni ko'rsatadigan misol:

#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) {
        // Istisno tashlaymiz - MyException sinfi ob'ekti
        throw MyException(-1);
    }
    if (val == 0) {
        // Standart istisno tashlaymiz - std::runtime_error sinfi ob'ekti
        throw std::runtime_error("Qiymat nolga teng bo'lishi mumkin emas.");
    }
    std::cout << "Qiymat musbat: " << val << std::endl;
}

int main() {
    try {
        test_func(-5);
    } catch (const MyException& e) {
        // MyException turidagi istisnani ushlaymiz
        std::cerr << "MyException bilan ushlandi, kod: " << e.get_code() << std::endl;
    } catch (const std::runtime_error& e) {
        // std::runtime_error turidagi istisnani ushlaymiz
        std::cerr << "std::runtime_error bilan ushlandi: " << e.what() << std::endl;
    } catch (...) {
        // Har qanday boshqa istisnani ushlaymiz
        std::cerr << "Noma'lum istisno ushlandi." << std::endl;
    }

    try {
        test_func(0);
    } catch (const std::exception& e) {
        // Standart istisnalar uchun asosiy sinfni ushlash mumkin
        std::cerr << "Standart istisno ushlandi: " << e.what() << std::endl;
    }

    return 0;
}