A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/c/c-program-to-handle-divide-by-zero-and-multiple-exceptions/ below:

C Program to Handle Divide by Zero

C Program to Handle Divide by Zero

Last Updated : 23 Jul, 2025

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.

There are 2 methods to handle divide-by-zero exception mentioned below:

Manually Checking before Division

The most used method is to check if the divisor (number that divides the dividend) in the division is zero or not using if else statement.

Example:

C
#include <stdio.h>
#include <float.h>

int main() {
    float a = 10, b = 0;
    float res;
    
    // Check division by zero
    if(b == 0){
        printf("Error: Division by zero");
    }else{
        res = a / b;
        printf("%f", res);
    }
    return 0;
}

Output
Error: Division by zero

Explanation: The program checks for division by zero using if (b == 0) before performing the division. If b is 0, it prints an error message.

Using Signal Handling

Signal handling can be used to catch runtime exceptions like divide-by-zero errors. In case of floating-point errors, SIGFPE (Floating Point Exception) is raised. We can create a signal handler function and assign it to SIGFPE using signal() function. The setjump and longjmp can be used to jump to the previous valid state of the program, allowing you to handle the exception and resume execution. The SIGFPE can be cleared by using the feclearexcept and fetestexcept functions from the fenv.h header

Example:

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

jmp_buf recovery;

void handle_divide_by_zero(int sig)  {

	// Re-assign the signal handler 
	signal(SIGFPE, handle_divide_by_zero);
	printf("Error: Division by zero\n");
	
	// Jump to the recovery point 
	longjmp(recovery, 1); 
}
int main() { 
	double a = 10, b = 0, res; 
	int recovery_status;

	// Assign the signal handler 
	signal(SIGFPE, handle_divide_by_zero); 

	// Set a recovery point 
	recovery_status = setjmp(recovery); 
	if (recovery_status == 0) {
	    res  = a / b;
	    if(fetestexcept(FE_DIVBYZERO)) {
	        feclearexcept(FE_DIVBYZERO);
		    raise(SIGFPE);
	    }
		else {
		    printf("%f", res);
		}
	}
	return 0; 
}

Explanation: Program executes step by step as follow:



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4