C Program to Handle Divide By Zero and Multiple Exceptions
Last Updated :
14 May, 2023
In C programming, there is no built-in exception handling like in other high-level languages such as C++, Java, or Python. However, you can still handle exceptions using error checking, function return values, or by using signal handlers. In this answer, we’ll discuss two methods for handling exceptions in C, particularly handling divide-by-zero errors.
Methods to Handle Divide by Zero and Multiple Exceptions
There are 2 methods to handle divide-by-zero exceptions mentioned below:
- Error checking and function return values
- Signal handling
1. Error checking and function return values
In this method, we use return values of functions to indicate if an error has occurred. We can write a custom function that checks for divide-by-zero exceptions and returns an error code if it occurs.
Example:
C
#include <stdbool.h>
#include <stdio.h>
bool safe_divide( double num, double denom, double * result)
{
if (denom == 0) {
return false ;
}
*result = num / denom;
return true ;
}
int main()
{
double numerator, denominator, quotient;
printf ( "Enter numerator: " );
scanf ( "%lf" , &numerator);
printf ( "Enter denominator: " );
scanf ( "%lf" , &denominator);
if (safe_divide(numerator, denominator, "ient)) {
printf ( "The quotient is: %.2lf\n" , quotient);
}
else {
printf ( "Error: Division by zero is not allowed.\n" );
}
return 0;
}
|
Output:
Enter numerator: 10
Enter denominator: 0
Error: Division by zero is not allowed.
2. Signal handling
Signal handling can be used to catch hardware exceptions like divide-by-zero errors. When a signal is raised, the program jumps to a specified signal handling function. by using the feclearexcept and fetestexcept functions from the fenv.h header. This version checks for floating-point exceptions explicitly and handles them accordingly.
Example:
C
#include <fenv.h>
#include <setjmp.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
jmp_buf recovery;
void handle_divide_by_zero( int sig)
{
signal (SIGFPE, handle_divide_by_zero);
printf ( "Error: Division by zero is not allowed.\n" );
longjmp (recovery, 1);
}
int main()
{
double numerator, denominator, quotient;
int recovery_status;
signal (SIGFPE, handle_divide_by_zero);
printf ( "Enter numerator: " );
scanf ( "%lf" , &numerator);
printf ( "Enter denominator: " );
scanf ( "%lf" , &denominator);
recovery_status = setjmp (recovery);
if (recovery_status == 0) {
feclearexcept(FE_ALL_EXCEPT);
quotient = numerator / denominator;
if (fetestexcept(FE_DIVBYZERO)) {
raise (SIGFPE);
}
else {
printf ( "The quotient is: %.2lf\n" , quotient);
}
}
return 0;
}
|
Output:
Enter numerator: 10
Enter denominator: 0
Error: Division by zero is not allowed.
Share your thoughts in the comments
Please Login to comment...