Middle
Ar ko tiek glabātas izņēmumi C++?
sobes.tech AI
Atbilde no AI
Ar objektiem. Izmetot izņēmumu ar throw, tiek izveidots pagaidu objekts, kas pēc tam tiek nodots izņēmumu apstrādes mehānismam. Šī objekta tips nosaka, kurš catch apstrādātājs tiks izvēlēts.
Šeit ir piemērs, kā demonstrēt izņēmumu saglabāšanu kā objektiem:
#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) {
// Izmet izņēmumu - MyException klases objekts
throw MyException(-1);
}
if (val == 0) {
// Izmet standarta izņēmumu - std::runtime_error klases objekts
throw std::runtime_error("Value cannot be zero.");
}
std::cout << "Vērtība ir pozitīva: " << val << std::endl;
}
int main() {
try {
test_func(-5);
} catch (const MyException& e) {
// Noķer izņēmumu pēc MyException objekta tipa
std::cerr << "Noķerts MyException ar kodu: " << e.get_code() << std::endl;
} catch (const std::runtime_error& e) {
// Noķer izņēmumu pēc std::runtime_error objekta tipa
std::cerr << "Noķerts std::runtime_error: " << e.what() << std::endl;
} catch (...) {
// Noķer jebkuru citu izņēmumu
std::cerr << "Noķerts nezināms izņēmums." << std::endl;
}
try {
test_func(0);
} catch (const std::exception& e) {
// Var noķert bāzes klasi standarta izņēmumiem
std::cerr << "Noķerts standarta izņēmums: " << e.what() << std::endl;
}
return 0;
}