Exception handling က program run နေချိန်မှာ error ဖြစ်နိုင်တဲ့အခြေအနေတွေကို လှလှပပကိုင်တွယ်ဖို့ သုံးပါတယ်။ File မတွေ့တာ၊ invalid input ရတာ၊ divide by zero ဖြစ်တာလို case တွေမှာ program တစ်ခုလုံး crash မဖြစ်အောင် try, throw, catch နဲ့ ဖြေရှင်းနိုင်ပါတယ်။
cpp
#include <iostream>
using namespace std;
int main() {
try {
int age = 15;
if (age < 18) {
throw string("You must be at least 18 years old.");
}
cout << "Access granted.";
} catch (string message) {
cout << "Access denied: " << message;
}
return 0;
}try ထဲမှာ error ဖြစ်နိုင်တဲ့ logic ကို ထည့်ထားပါတယ်။ Age မပြည့်ရင် throw နဲ့ error message ပစ်လွှတ်ပြီး catch က လက်ခံကိုင်တွယ်ပါတယ်။
You should see
Access denied: You must be at least 18 years old.Info
Exception က မျှော်လင့်ထားတဲ့ error flow တွေအတွက်ပါ။ ပုံမှန် condition check အားလုံးကို exception နဲ့ မရေးသင့်ပါ။