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:

  • When you inherit from std::exception, you adhere to a well-defined interface that other C++ developers expect. This makes your code more readable and easier to integrate with other libraries or codebases.

2. Polymorphic Handling:

  • std::exception acts as a base class for various exception types. By deriving from it, you allow catching your custom exception through a catch (std::exception& e) block. This is crucial for handling different exception types in a generalized way.

3. Richer Exception Information:

  • std::exception provides the what() virtual function, which you've overridden in your example. However, other subclasses like std::runtime_error, std::logic_error, etc., offer more specific exception categories, making it easier to understand the nature of the error.

4. Exception Safety and Resource Management:

  • In more complex scenarios, destructors of objects involved in an exception might need to be called during stack unwinding. Deriving from std::exception ensures that your exception objects are handled correctly in such situations, preventing resource leaks.

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;
}
        

要查看或添加评论,请登录

M Vijaynath的更多文章

社区洞察

其他会员也浏览了