Middle
Millega salvestatakse C++-is erandid?
sobes.tech AI
Vastus AI-lt
Objektide abil. Kui visata erand throw abil, luuakse ajutine objekt, mis seejärel edastatakse erandite töötlemise mehhanismile. Selle objekti tüüp määrab, milline catch töötleja valitakse.
Siin on näide, kuidas näidata erandite salvestamist objektidena:
#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) {
// Viska erand - MyException klassi objekt
throw MyException(-1);
}
if (val == 0) {
// Viska standardne erand - std::runtime_error klassi objekt
throw std::runtime_error("Value cannot be zero.");
}
std::cout << "Väärtus on positiivne: " << val << std::endl;
}
int main() {
try {
test_func(-5);
} catch (const MyException& e) {
// Püüa erand MyException objekti tüübi järgi
std::cerr << "Püüdsin MyExceptioni koodiga: " << e.get_code() << std::endl;
} catch (const std::runtime_error& e) {
// Püüa erand std::runtime_error objekti tüübi järgi
std::cerr << "Püüdsin std::runtime_error: " << e.what() << std::endl;
} catch (...) {
// Püüa mis tahes muu erand
std::cerr << "Püüdsin tundmatu erandi." << std::endl;
}
try {
test_func(0);
} catch (const std::exception& e) {
// Võib püüda standardsete erandite baasklassi
std::cerr << "Püüdsin standardse erandi: " << e.what() << std::endl;
}
return 0;
}