C++ exceptions
Exceptions เป็นวิธีที่จะจัดการกับโปรแกรมเพื่อให้ไปทำอย่างอื่นเมื่อมีข้อผิดพลาดเกิด ขึ้น โปรแกรมจะพยายามทำบางอย่างที่เราได้ระบุไว้ ถ้ามีข้อผิดพลาดเกิดขึ้น โปรแกรมจะย้ายไปทำงานอีกส่วนของโปรแกรมที่เรียกว่าฟังก์ชันตัวจัดการ Exceptions มีรูปแบบดังนี้:try
{
// statetments
}
catch (exceoption e1) {
// exception handler 1
}
catch (exceoption e2) {
// exception handler 2
}
...
ถ้า
เราไม่ใช้ exception ในโปรแกรมของเรา มันอาจจะเผชิญกับข้อผิดพลาด เช่น
running time errors หรือ memory allocation errors มี 3 คำสั่งเกี่ยวกับ
exception คือ thrown, try และ catch#include <iostream>
using namespace std;
int main ()
{
int n = 0;
try {
if (n == 0)
throw n;
else
cout << "n is not zero." << endl;
} catch (int e) {
cout << "An exception occurred: n = " << e << endl;
}
return 0;
}
ในตัวอย่าง โปรแกรมนั้นมีการจัดการกับข้อผิดพลาด ในบล็อคคำสั่งของ try โปรแกรมของเราจะตรวจสอบว่า n เป็น 0 เราจะใช้คำสั่ง throw ซึ่งมี n อากิวเมนต์ที่จะส่งต่อไปยังบล็อคคำสั่งของ catch
(handlers function) ประเภทของพารามิเตอร์จะต้องตรงกัน ในตัวอย่างนี้
เราได้ส่ง n ซึ่งเป็นข้อมูบแบบ int ฟังก์ชัน catch
จะต้องมีพารามิเตอร์เป็นแบบ int e ด้วยเช่นกันฟังก์ชัน catch สามารถเป็นฟังก์ชันแบบ overloaded ได้โดยการที่มันมีประเภทของพารามิเตอร์ที่แตกต่างกัน คอมไพลเลอร์จะทำการตัดสินใจว่าจะส่งไปที่ฟังก์ชันไหนเมื่อโปรแกรมทำงาน Overloaded handlers ได้สร้างขึ้นในรูปแบบเหมือนข้างบน นี่เป็นตัวอย่าง
try
{ throw 10.0;
}
catch (int e1)
{
// catch integer exception
}
catch (float e2)
{
// catch floating point exception
}catch (string e2)
{
// catch string exception
}
...
Standard exceptions
ใน ภาษา C++ มีไลบรารี่ของ exceptions มาตรฐานสำหรับการใช้งาน ซึ่งมันจะตัดสินใจอัตโนมัติเมื่อเกิดข้อผิดพลาดขึ้น และจะไปยังส่วนของโปรแกรมที่มีฟังก์ชัน catch ที่เหมาะสม ไลบรารี่สามารถใช้ได้โดยการ include std standard<exception> มายังโปรแกรมไลบรารี่มาตรฐานของ exceptions ในภาษา C++ แสดงดังรายการข้างล่าง:
| exception | description |
|---|---|
| bad_alloc | thrown by new on allocation failure |
| bad_cast | thrown by dynamic_cast when it fails in a dynamic cast |
| bad_exception | thrown by certain dynamic exception specifiers |
| bad_typeid | thrown by typeid |
| bad_function_call | thrown by empty function objects |
| bad_weak_ptr | thrown by shared_ptr when passed a bad weak_ptr |
| logic_error | error related to the internal logic of the program |
| runtime_error | error detected during runtime |
ไม่มีความคิดเห็น:
แสดงความคิดเห็น