MCAWALA

C++ Vertical Menu

C++ Programming Topics

Exception Handling in C++ (अपवाद प्रबंधन)

Exception Handling क्या है?

जब कोई प्रोग्राम चलाते समय कोई unexpected error (अपवाद) होता है, जैसे division by zero या file न मिलना, तो उसे handle करने का तरीका Exception Handling कहलाता है। इससे प्रोग्राम crash नहीं होता और हम error को सही तरीके से manage कर सकते हैं।

C++ में Exception Handling के मुख्य keywords:

  • try – वह block जहां error हो सकता है।
  • throw – error (exception) को फेंकना।
  • catch – error को पकड़ना और उसे handle करना।

Example (C++ Code):


#include <iostream>
using namespace std;

int division(int a, int b) {
    if (b == 0) {
        throw "Division by zero error!";
    }
    return a / b;
}

int main() {
    int x = 10, y = 0;
    try {
        int result = division(x, y);
        cout << "Result: " << result << endl;
    }
    catch (const char* msg) {
        cout << "Error: " << msg << endl;
    }

    cout << "Program continues after exception handling." << endl;
    return 0;
}
        

इसका आउटपुट होगा:


Error: Division by zero error!
Program continues after exception handling.
        

Summary (सारांश):

  • try block में वो कोड लिखा जाता है जिसमें error हो सकता है।
  • throw से exception फेंका जाता है।
  • catch block में exception को पकड़ कर सही handling करते हैं।
  • Exception handling से प्रोग्राम crash होने से बचता है।