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
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
. main()
function, we create a Shape*
pointer pointing to a Square
object. 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. 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!