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

การจับ Exception ทั้งหมดใน C++

Exception คือปัญหาที่เกิดระหว่างรันโปรแกรม ใช้ Try-Catch Block เพื่อจัดการ

ใช้ catch(...) เพื่อจับ Exception ทุกประเภท (Catch-all Handler)

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

#include <iostream>
using namespace std;

void func(int a) {
    try {
        if (a == 0) throw 23.33;
        if (a == 1) throw 's';
    } catch(...) {
        cout << "Caught Exception!\n";
    }
}

int main() {
    func(0);
    func(1);
    return 0;
}

ผลลัพธ์

Caught Exception!
Caught Exception!

catch(...) จับได้ทั้ง double และ char ที่โยนมา ควรวาง catch(...) สุดท้ายหลัง catch แบบเฉพาะเจาะจง