Build a C program to divide two numbers using try catch block ?

Build a C program to divide two numbers using a try-catch block?

The first thing is that there is no exception handling mechanism in C programming language like C++, JAVA, PYTHON, etc.

So, you cannot handle exception in C like C++ or JAVA, etc. but there is another solution is we can use longjmp AND setjmp.


longjmp and setjmp are defined in setjmp.h header file.


A solution of Build a C program to divide two numbers using a try-catch block


#include<stdio.h>
#include<setjmp.h>
#define TRY do{ jmp_buf ex_buf__; if( !setjmp(ex_buf__) ){
#define CATCH } else {
#define ETRY } }while(0)
#define THROW longjmp(ex_buf__, 1)
int main(int argc, char** argv)
{
int a,b,c;
clrscr();
   TRY
   {
      printf("Enter a First number = ");
      scanf("%d", &a);
      printf("\nEnter a Second number = ");
      scanf("%d", &b);
      if(b==0)
      {
      THROW;
      }
      else{
       c = a/b;
       printf("\nResult of %d / %d = %d",a,b,c);
      }
   }
   CATCH
   {
      printf("\nDivide by zero is invalid or exception!..\n");
   }
   ETRY;
   getch();
   return 0;
}

Output - :


Build a C program to divide two numbers using a try-catch block

Build a C program to divide two numbers using a try-catch block

No comments