Middle
Kaip saugomos išimtys C++?
sobes.tech AI
Atsakymas iš AI
Su objektais. Išmetus išimtį naudojant throw, sukuriamas laikinas objektas, kuris vėliau perduodamas išimtinių įvykių valdymo mechanizmui. Šio objekto tipas lemia, kuris catch apdorotojas bus pasirinktas.
Štai pavyzdys, kuris parodo, kaip išsaugoti išimtis kaip objektus:
#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) {
// Išmetame išimtį - MyException klasės objektą
throw MyException(-1);
}
if (val == 0) {
// Išmetame standartinę išimtį - std::runtime_error klasės objektą
throw std::runtime_error("Reikšmė negali būti lygi nuliui.");
}
std::cout << "Reikšmė teigiama: " << val << std::endl;
}
int main() {
try {
test_func(-5);
} catch (const MyException& e) {
// Gaudome išimtį pagal MyException objekto tipą
std::cerr << "MyException pagauta, kodas: " << e.get_code() << std::endl;
} catch (const std::runtime_error& e) {
// Gaudome išimtį pagal std::runtime_error objekto tipą
std::cerr << "std::runtime_error pagauta: " << e.what() << std::endl;
} catch (...) {
// Gaudome bet kokią kitą išimtį
std::cerr << "Nežinoma išimtis pagauta." << std::endl;
}
try {
test_func(0);
} catch (const std::exception& e) {
// Galima pagauti bazinį klasės tipą standartinėms išimtims
std::cerr << "Standartinė išimtis pagauta: " << e.what() << std::endl;
}
return 0;
}