First principles of C++: Exception handling
#include <iostream>
class MyException {
public:
const char *what() {
return "hello";
}
};
int main() {
try{
throw MyException();
}
catch (MyException &e){
std::cout <<e.what();
}
return 0;
}
While the above example provided works perfectly fine for throwing and catching exceptions. However, deriving from std::exception (or one of its subclasses) offers several advantages and is generally considered good practice:
1. Standard Interface and Familiarity:
2. Polymorphic Handling:
领英推荐
3. Richer Exception Information:
4. Exception Safety and Resource Management:
Here is better way to do,
#include <iostream>
#include <exception>
// Custom exception class for a specific error condition
class InvalidInputError : public std::runtime_error {
public:
InvalidInputError(const std::string& message)
: std::runtime_error(message) {}
};
int main() {
try {
int age;
std::cout << "Enter your age: ";
std::cin >> age;
if (age < 0) {
throw InvalidInputError("Age cannot be negative.");
}
// ... other code using the valid age ...
} catch (const InvalidInputError& e) {
std::cerr << "Invalid input: " << e.what() << std::endl;
} catch (const std::exception& e) {
std::cerr << "General exception: " << e.what() << std::endl;
}
return 0;
}