C++中的异常处理和对象销毁


C++ 中的析构函数一般在对象销毁并从系统中释放内存时调用。在类的异常中抛出异常时,析构函数将在捕获块执行前自动调用。

算法

Begin
   Declare a class sample1.
      Declare a constructor of sample1.
         Print “Construct an Object of sample1”
      Declare a destructor of sample1.
         Print “Destruct an Object of sample1”
   Declare a class sample.
      Declare a constructor of sample2.
         Declare variable i of the integer datatype.
         Initialize i = 7.
         Print “Construct an Object of sample1”.
         Throw i.
      Declare a destructor of sample2.
         Print “Destruct an Object of sample2”
   Try:
      Declare an object s1 of class sample1.
      Declare an object s2 of class sample2.
   Ctach(int i)
      Print “Caught”.
      Print the value of variable i.
End.

示例代码

 现场演示

#include <iostream>
using namespace std;
class Sample1 {
   public:
      Sample1() {
         cout << "Construct an Object of sample1" << endl;
      }
      ~Sample1() {
         cout << "Destruct an Object of sample1" << endl;
      }
};
class Sample2 {
   public:
      Sample2() {
         int i =7;
         cout << "Construct an Object of sample2" << endl;
         throw i;
      }
      ~Sample2() {
         cout << "Destruct an Object of sample2" << endl;
      }
};
int main() {
   try {
      Sample1 s1;
      Sample2 s2;
   } catch(int i) {
      cout << "Caught " << i << endl;
   }
}

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

输出

Construct an Object of sample1
Construct an Object of sample2
Destruct an Object of sample1
Caught 7

更新于: 2019-7-30

694 次浏览

开启你的 职业生涯

完成课程并获得认证

开始学习
广告