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

พื้นฐาน Exception Handling ใน C++

บทนำ

ใน C++ Exception Handling เป็นกระบวนการจัดการ runtime errors Exception คือเหตุการณ์ที่ถูกโยน (thrown) ในขณะรันไทม์ ทุก exception มาจากคลาส std::exception เป็น runtime error ที่จัดการได้ พิมพ์ข้อความ exception และจบโปรแกรม หากเราไม่จัดการ exception

Exceptions ถูกนิยามในมาตรฐาน C++ เป็นคลาส <exception> ที่เราสามารถใช้ในโปรแกรมได้ โครงสร้าง parent-child class hierarchy แสดงดังรูป (รูปไม่ได้รวมในข้อความนี้)

Exception Classes ทั่วไปใน C++

Exception คำอธิบาย
std::exceptionคลาสพ่อของทุก standard C++ exceptions
std::bad_castexception ที่โยนโดย dynamic_cast
std::bad_exceptionจัดการ unexpected exceptions ในโปรแกรม C++
std::bad_allocมักโยนโดย new
std::logic_failureexception ที่ตรวจพบได้จากการอ่านโค้ด
std::runtime_errorexception ที่ตรวจพบไม่ได้จากการอ่านโค้ด
std::bad_typeidexception ที่โยนโดย typeid

คีย์เวิร์ด

มี 3 คีย์เวิร์ดใน exception handling: try, catch และ throw

Try/Catch Block

ใน C++ exception handling ทำด้วย try/catch statement โค้ดที่อาจเกิด exception วางใน try block catch block ใช้จัดการ exception

ตัวอย่างโค้ด

#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;
    }
    return 0;
}

ผลลัพธ์

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

User Defined Exception

เราสามารถกำหนด exception เองได้โดยสืบทอดและ override ฟังก์ชันของ exception class

ตัวอย่างโค้ด

#include <iostream>
#include <exception>
using namespace std;

struct DivideByZero : public exception {
    const char* what() const throw() {
        return "My Exception";
    }
};

int main() {
    try {
        throw DivideByZero();
    } catch (DivideByZero& e) {
        cout << "Exception caught" << endl;
        cout << e.what() << endl;
    } catch (exception& e) {
    }
    return 0;
}

ผลลัพธ์

Exception caught
My Exception

what() เป็น public method ของ exception class ถูก override โดยทุก child exception classes คืนค่าสาเหตุของ exception