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 turant 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 do, 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 run hote hain, isliye resources clean up ho jaate hain chahe ek exception ek function ko beech mein hi kyun na kaat de.
Yahi hai C++ ki foundation: hamesha copy kiye bina 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 next step hai practice — ek chhota program pick karo aur use banao, is baat par dhyan dete hue ki har resource ka owner kaun hai aur woh kab clean up hota hai.
Practice exercise
Ek function safeDivide(double a, double b) likho jo ek runtime_error("cannot divide by zero") throw kare agar b 0 ho, warna a / b return kare. Use ek try/catch ke andar (10, 0) ke saath call karo, aur caught exception ka message print karo.