Show List

Error Handling

In C, error handling refers to the techniques used to handle errors that occur in a program. There are several ways to handle errors in C, including the following:

  • Return values: Functions can return a value indicating whether they have executed successfully or not. For example, the fopen function returns a non-null pointer to a file stream if the file is successfully opened, and a null pointer if an error occurs.

Example:

scss
Copy code
FILE *fp; fp = fopen("file.txt", "r"); if (fp == NULL) { printf("Error opening file\n"); exit(1); }
  • Global variables: Programs can use global variables to indicate the success or failure of a function. For example, the errno global variable is set to a non-zero value if an error occurs in a library function.

Example:

c
Copy code
#include <errno.h> #include <math.h> int main() { double result; result = sqrt(-1); if (errno == EDOM) { perror("sqrt"); exit(1); } return 0; }
  • Exception handling: The setjmp and longjmp functions can be used to implement exception handling in C, which is a mechanism for handling errors or exceptional conditions in a program.

Example:

c
Copy code
#include <setjmp.h> #include <stdio.h> jmp_buf buf; void do_something() { longjmp(buf, 1); } int main() { if (setjmp(buf) == 0) { printf("Before call to do_something\n"); do_something(); } else { printf("After call to do_something\n"); } return 0; }

In this example, the setjmp function is used to set a jump point, and the longjmp function is used to jump back to that point if an error occurs. The do_something function calls longjmp to trigger the jump, and the program resumes execution at the point specified by setjmp.

These are some of the ways to handle errors in C. It's important to handle errors properly in your code to ensure that your program runs as expected and produces meaningful results, even in the presence of errors.


    Leave a Comment


  • captcha text