Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

การโยน Exception จาก Constructor ใน C++


การโยน Exception จาก Constructor ใน C++

นี่คือตัวอย่างง่ายๆ ของการโยน exception จาก constructor ใน C++

อัลกอริทึม

Begin
    ประกาศคลาส sample1
        Constructor: พิมพ์ "Construct an Object of sample1"
        Destructor: พิมพ์ "Destruct an Object of sample1"
    ประกาศคลาส sample2
        Constructor: ตัวแปร i = 7, พิมพ์ "Construct an Object of sample2", โยน i
        Destructor: พิมพ์ "Destruct an Object of sample2"
    Try:
        สร้างออบเจ็กต์ s1 ของ sample1
        สร้างออบเจ็กต์ s2 ของ sample2
    Catch(int i)
        พิมพ์ "Caught" และค่า 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;
    }
}

ผลลัพธ์

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