Exceptions aur Error Handling
Ek function jise ek aisa error milta hai jise woh locally handle nahi kar sakta, woh ek exception throw kar sakta hai — execution foran call stack ko tab tak unwind karta hai jab tak use ek matching catch block na mil jaaye. Agar kahin bhi koi matching catch na ho, to throw program ko terminate kar deta hai.
#include <iostream>
#include <stdexcept>
using namespace std;
double divide(double a, double b) {
if (b == 0) {
throw runtime_error("cannot divide by zero");
}
return a / b;
}
int main() {
try {
cout << divide(10, 2) << endl;
cout << divide(10, 0) << endl;
} catch (const runtime_error& e) {
cout << "Error: " << e.what() << endl;
}
return 0;
}5 Error: cannot divide by zero
Dhyan rahe, divide(10, 2) apna result normally print karta hai, lekin divide(10, 0) return hone se pehle hi throw kar deta hai — execution seedha catch block mein jump kar jaata hai, try block ke baaki hisse ko completely skip karte hue. Jab stack raaste mein kisi bhi RAII objects se guzarte hue unwind hota hai, to unke destructors phir bhi normally chalte hain, isliye resources clean up ho jaate hain chahe ek exception ek function ko beech mein hi kyun na kaat de.
Yehi hai C++ ki foundation: hamesha copy kiye baghair flexible access ke liye references aur pointers, bina garbage collector ke deterministic resource cleanup ke liye RAII, polymorphism ke liye virtual dispatch wali classes, aur compile-time generic code ke liye templates. Yahan se, best agla qadam hai mashq — ek chhota program chuno aur use banao, is baat par dhyan dete hue ke har resource ka owner kaun hai aur woh kab clean up hota hai.
Practice exercise
Ek function safeDivide(double a, double b) likhein jo ek runtime_error("cannot divide by zero") throw kare agar b 0 ho, warna a / b wapas kare. Use ek try/catch ke andar (10, 0) ke sath call karein, aur caught exception ka message print karein.