Middle
C++-də istisnalar necə saxlanılır?
sobes.tech Süni İntellekt
AI-dan cavab
Obyektlərlə. throw istifadə edilərək istisna atıldıqda, müvəqqəti obyekt yaradılır və sonra istisna idarəetmə mexanizmasına ötürülür. Bu obyektin tipi hansı catch tutucusunun seçiləcəyini müəyyən edir.
Budur, obyektlər şəklində istisnaların necə saxlanılmasını göstərən nümunə:
#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ırıq - MyException sinfi obyekti
throw MyException(-1);
}
if (val == 0) {
// Standart istisna atırıq - std::runtime_error sinfi obyekti
throw std::runtime_error("Dəyər sıfır ola bilməz.");
}
std::cout << "Dəyər müsbətdir: " << val << std::endl;
}
int main() {
try {
test_func(-5);
} catch (const MyException& e) {
// MyException tipli istisnayı tuturuq
std::cerr << "MyException tutundu, kod: " << e.get_code() << std::endl;
} catch (const std::runtime_error& e) {
// std::runtime_error tipli istisnayı tuturuq
std::cerr << "std::runtime_error tutundu: " << e.what() << std::endl;
} catch (...) {
// Hər hansı digər istisnayı tuturuq
std::cerr << "Naməlum istisna tutundu." << std::endl;
}
try {
test_func(0);
} catch (const std::exception& e) {
// Standart istisnalar üçün əsas sinfi tutmaq olar
std::cerr << "Standart istisna tutundu: " << e.what() << std::endl;
}
return 0;
}