Translate

C Program to Handle Divide by Zero - Divide by Zero रोकने के उपाय

परिचय

C प्रोग्रामिंग में Divide by Zero Error एक आम समस्या है जो नए और experienced programmers दोनों के लिए चुनौती बन सकती है। सोचिए अगर आपके financial या scientific calculation में denominator गलती से zero हो जाए, तो आपका पूरा program crash कर सकता है। इस ब्लॉग में हम सीखेंगे कि किस तरह C program में divide by zero को handle किया जाए, practical examples के साथ।

Divide by Zero क्या है?

Divide by zero तब होता है जब हम किसी number को zero से divide करने की कोशिश करते हैं। C में यह runtime error के रूप में सामने आता है। Example:


int a = 10;
int b = 0;
int result = a / b; // Divide by Zero Error
        

यहाँ b = 0 होने के कारण आपका program crash कर सकता है। इसलिए इसे handle करना ज़रूरी है।

Divide by Zero को Handle क्यों करें?

  • Program crash रोकें: User experience बेहतर बनता है।
  • Data integrity सुरक्षित रखें: Financial या sensitive calculation में error avoid होती है।
  • Debugging आसान बनाएं: Error messages clear हों।

C Program Example

नीचे एक simple C program example है जो divide by zero error को safely handle करता है:


#include <stdio.h>

int main() {
    int numerator, denominator;
    float result;

    printf("Enter numerator: ");
    scanf("%d", &numerator);

    printf("Enter denominator: ");
    scanf("%d", &denominator);

    if (denominator == 0) {
        printf("Error: Divide by Zero नहीं किया जा सकता।\n");
    } else {
        result = (float)numerator / denominator;
        printf("Result: %.2f\n", result);
    }

    return 0;
}
        

Actionable Insight: हमेशा denominator को check करें if (denominator == 0) से पहले division करने से आपका program crash नहीं होगा।

C Program to Handle Divide by Zero - Divide by Zero रोकने के उपाय

Advanced Error Handling: Signal Handling और Try‑Catch जैसे Mechanism in C

C language में Java या C++ जैसा built‑in try‑catch नहीं होता है, लेकिन हम इसे simulate कर सकते हैं signal(), setjmp() और longjmp() के साथ। इसके ज़रिये हम runtime‑level exceptions जैसे divide by zero को gracefully detect और handle कर सकते हैं, जिससे program crash न हो।

1. Signal Handler Setup (SIGFPE)

जब floating point या arithmetic exception होता है, तो OS process में SIGFPE signal भेजता है। हम custom signal handler set करके division error को catch कर लेते हैं।


#include <stdio.h>
#include <signal.h>
#include <setjmp.h>
#include <fenv.h>

jmp_buf recover;

/* Signal handler for divide by zero */
void handle_div_error(int sig) {
    printf("📌 Error: Divide by Zero detected! (caught by signal handler)\n");
    longjmp(recover, 1);  // return to recovery point
}

int main() {
    double num = 10.0, den = 0.0, res;

    /* Assign handler */
    signal(SIGFPE, handle_div_error);

    /* Set recovery checkpoint */
    if (setjmp(recover) == 0) {
        /* Attempt division */
        res = num / den;  // may cause floating point exception
        if (fetestexcept(FE_DIVBYZERO)) {
            /* Raise SIGFPE if divide by zero occurred */
            raise(SIGFPE);
        } else {
            printf("Result = %.2f\n", res);
        }
    }
    return 0;
}
    

Explanation:

  • पहले हम signal(SIGFPE, handler) से handler set करते हैं।
  • setjmp() recovery checkpoint बनाता है ताकि longjmp() के बाद program फिर से continue हो सके।
  • अगर floating point zero division detect होता है, तो handler को call किया जाता है और program safe तरीके से error message देता है।

2. Simulating Try‑Catch Behaviour in C

C में real try/catch नहीं होता है, पर हम language के built‑in features के साथ इसे simulate कर सकते हैं — जो कुछ high‑level error handling जैसा काम करता है। ऐसा mechanism setjmp/longjmp के combination से बनता है। (source inspired by community discussions) :contentReference[oaicite:3]{index=3}


#include <stdio.h>
#include <setjmp.h>
#include <signal.h>

jmp_buf context;

void sigfpe_handler(int sig) {
    printf("⚠️ Exception: Floating point error (division by zero)\n");
    longjmp(context, 1);
}

int safeDivide(int a, int b) {
    if (b == 0) {
        /* simulate throwing an exception */
        raise(SIGFPE);
    }
    return a / b;
}

int main() {
    int result;

    /* set signal handler */
    signal(SIGFPE, sigfpe_handler);

    if (setjmp(context) == 0) { /* TRY block */
        result = safeDivide(20, 0);
        printf("Result is %d\n", result);
    } else {
        /* CATCH block */
        printf("→ Caught divide by zero - recovering safely!\n");
    }
    return 0;
}
    

Key Insight: यह pattern “try‑catch” जैसा control flow देता है — TRY में risky code डालते हैं और CATCH की तरह longjmp के बाद alternate logic चलाते हैं।

3. जब Use करें Error Handling?

  • जब आपका program real‑time user input ले रहा है।
  • जब division operations dynamic values से हों।
  • जब crash से बेहतर graceful failure चाहिए।

ध्यान दें कि signal handlers advanced हैं — इन्हें सिर्फ तभी use करें जब normal input validation (जैसे if (den==0)) पर्याप्त न हो।

Frequently Asked Questions (FAQ)

1. Divide by Zero क्या है?

Divide by Zero तब होता है जब कोई number zero से divide किया जाता है। C में यह runtime error पैदा करता है।

2. C में Divide by Zero कैसे रोकें?

Denominator को check करें कि वह zero न हो। अगर zero है, तो error message दिखाएँ और division न करें।

3. Divide by Zero error के कारण क्या हो सकते हैं?

Program crash, गलत calculation, और debugging में दिक्कतें हो सकती हैं।

4. क्या floating point division से यह error avoid हो सकता है?

Floating point division integer truncation को रोक सकता है, लेकिन denominator zero होने पर error फिर भी आएगी। Input validation जरूरी है।

5. Real-world example में Divide by Zero कैसे handle करें?

Financial या scientific applications में user input validate करें और zero denominator होने पर fallback या warning message दें।

📌 Further reading

Post a Comment

Blogger

Your Comment Will be Show after Approval , Thanks

Support Our Content

Pay via UPI
Works with: GPay | PhonePe | Paytm | BHIM
anurajk.com@ptyes


More Payment Options / Scan QR →

Ads

 
↑ Top