Search code examples
cdivide-by-zero

How to replace "Floating point exception" error with an error of my own


I have an assignment from my school in which I'd enter 2 numbers which are 5 and 0 and divide it and a display result showing "Result is undefined - division by 0 is encountered".

This is my code:

#include <stdio.h>

int main() {
    int num, num2, sum, diff, pro, quo;
    int operation;
    
    printf("Enter 1st num: ");
    scanf("%d", &num);
    printf("Enter 2nd num: ");
    scanf("%d", &num2);
    printf("Choose Operation: ");
    printf("\n [1] Addition \n [2] Subtraction \n [3] Multiplication \n [4] Divison \n");
    printf("Choice: ");
    scanf("%d", &operation);
    
    sum = num + num2;
    diff = num - num2;
    pro = num * num2;
    quo = num / num2;
    
    switch(operation)
    {
    case 1:
        printf("Result of adding %d and %d is %d", num, num2, sum);
        break;

    case 2:
        printf("%d - %d = %d", num, num2, diff);
        break;

    case 3:
        printf("%d * %d = %d", num, num2, pro);
        break;

    case 4:
        switch(operation)
        {
        case 4:
            printf("%d / %d = %d", num, num2, quo);
            break;
        default:
            printf("Result is undefined - division by 0 is encountered");
        }
        break;
    }
    return 0;
}

Solution

  • That message is probably thrown due to the SIGFPE signal being raised. By including <signal.h>, you can handle the signal and print your own message. Here's an example.

    #include <signal.h>
    #include <stdlib.h>
    
    void handle(int sig)
    {
        puts("Result is undefined");
        exit(1);
    }
    
    int main(void)
    {
        signal(SIGFPE, handle);
        int a = 5 / 0;
    }
    

    Under normal circumstances, this printed Floating point exception for me, but with the signal handler, it prints a custom message and then exits. For me, if I don't exit immediately after printing, it prints my custom message infinitely, so removing the exit(1) may not be the best idea. Unfortunately, you cannot be certain if the signal was raised due to a divide-by-0 error, but in your program, it is likely to be the only cause.

    Alternatively, you could also just check if the divisor is 0 before you try dividing, in which case you could be certain it would be a divide-by-0 error.