Home >Backend Development >C++ >Exception handling in C++ technology: How to catch derived class exceptions through base class pointers?

Exception handling in C++ technology: How to catch derived class exceptions through base class pointers?

WBOY
WBOYOriginal
2024-05-09 17:39:01921browse

In C, derived class exceptions can be caught through base class pointers. Using virtual functions and try-catch blocks, we can: Throw a derived class exception Catch it using a base class pointer Automatically release the derived class object by deleting the base class pointer

C++ 技术中的异常处理:如何通过基类指针来捕获派生类异常?

Exception handling in C: Catching derived class exceptions through base class pointers

In C, exception handling is a mechanism for handling errors and exceptions. When an exception occurs, an exception object is thrown. Exception objects store information about the error, such as the error message and the location where the error occurred.

Catching derived class exceptions through a base class pointer is a flexible way to handle exceptions from derived classes. This is achieved using try-catch blocks and virtual functions.

Code example:

Suppose we have a base class Shape and a derived class Square. The Shape class has a virtual function GetArea(), which is overridden by the Square class.

class Shape {
public:
    virtual int GetArea() const = 0;
};

class Square : public Shape {
public:
    Square(int side) : side(side) {}
    int GetArea() const override { return side * side; }
private:
    int side;
};

int main() {
    try {
        Shape* shape = new Square(5);
        shape->GetArea();  // 抛出异常
    } catch (Shape* base_ptr) {
        // 捕获 Shape* 指针的基类指针
        delete base_ptr;  // 确保释放派生类对象
        std::cout << "异常捕获成功!" << std::endl;
    }

    return 0;
}

Explanation:

  • GetArea() throws an exception in the derived class Square.
  • In the main() function, we create a Shape* pointer pointing to a Square object.
  • When shape->GetArea() is called, it actually calls the overriding function of the derived class and throws an exception.
  • catch block uses the base class pointer base_ptr to catch the exception object.
  • By capturing the base class pointer, we can handle exceptions from derived classes.
  • Finally, we delete base_ptr and automatically release the pointer to the derived class object.

The above is the detailed content of Exception handling in C++ technology: How to catch derived class exceptions through base class pointers?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn