ในส่วนนี้ เราจะมาดูวิธีการใช้ catch block สำหรับการจัดการข้อยกเว้นและการแปลงประเภทใน C++
ขั้นแรก ให้เราดูโค้ด แล้วมาดูกันว่าผลลัพธ์จะเป็นอย่างไร และจะสร้างได้อย่างไร
ตัวอย่าง
#include <iostream>
using namespace std;
int main() {
try{
throw 'a';
}
catch(int a) {
cout << "Integer value is caught :" << a;
}
catch(...) {
cout << "Entering into default catch block";
}
} ผลลัพธ์
Entering into default catch block
ดังนั้นเหตุผลที่อยู่เบื้องหลังนี้คืออะไร เหตุใดจึงสร้างเอาต์พุตประเภทนี้ ดังที่เราเห็นตัวละคร 'a' ถูกโยนออกไป แต่บล็อก catch แรกมีไว้สำหรับ int หากเราคิดว่า ASCII ของ 'a' เป็นจำนวนเต็ม ก็จะเข้าสู่บล็อกแรก แต่การแปลงประเภทนั้นใช้ไม่ได้กับบล็อกที่ดักจับ
เรามาดูตัวอย่างอื่นกัน ในตัวอย่างนี้ เราจะเห็นว่าคอนสตรัคเตอร์ไม่ได้ถูกเรียกสำหรับอ็อบเจกต์ที่ถูกโยน
ตัวอย่าง
#include <iostream>
using namespace std;
class TestExcept1 {};
class TestExcept2 {
public:
TestExcept2 (const TestExcept1 &e ){ // Defining the Conversion constructor
cout << "From the Conversion constructor";
}
};
main() {
try{
TestExcept1 exp1;
throw exp1;
} catch(TestExcept2 e2) {
cout << "Caught TestExcept2 " << endl;
} catch(...) {
cout << "Entering into default catch block " << endl;
}
} ผลลัพธ์
Entering into default catch block
วัตถุประเภทที่ได้รับจะไม่ถูกแปลงเป็นวัตถุประเภทพื้นฐานในขณะที่วัตถุประเภทที่ได้รับจะถูกส่งออกไป