C Programming Error Handling | Codingque

Welcome to C Programming Tutorial

Your guide to getting started with C programming.

Error handling

Error handling is an essential part of programming that involves anticipating, detecting, and managing errors that might occur during program execution. In C, there are several techniques for handling errors. Below is an explanation with examples to illustrate how you can handle errors in your C programs.

Types of Errors

Compile-time Errors: Errors detected by the compiler, such as syntax errors or type mismatches.

Run-time Errors: Errors that occur during program execution, such as division by zero or accessing invalid memory.

Logical Errors: Errors where the program runs but produces incorrect results due to logic mistakes in the code.

Error Handling Techniques in C

1. Using errno

2. Return Codes

3. setjmp and longjmp

Using errno

The errno variable is a global variable set by system calls and some library functions in the event of an error to indicate what went wrong. You need to include <errno.h> to use errno.

#include <stdio.h>
#include <errno.h>
#include <string.h>

int main() {
    FILE *file;
    file = fopen("nonexistent.txt", "r");
    
    if (file == NULL) {
        printf("Error opening file: %s\n", strerror(errno));
        return 1;
    }
    
    fclose(file);
    return 0;
}
            

Header Files

#include <stdio.h>: This header file includes the standard input and output library functions such as printf and fopen.

#include <errno.h>: This header file defines the integer variable errno, which is set by system calls and some library functions in the event of an error to indicate what went wrong.

#include <string.h>: This header file includes functions for handling C strings, such as strerror, which converts error codes into human-readable messages.

Main Function

int main() { ... }: The main function is the entry point of the program. It returns an integer value to the operating system upon completion.

File Pointer Declaration

FILE *file;: This declares a pointer named file of type FILE. It will be used to refer to the file being opened.

Attempt to Open File

file = fopen("nonexistent.txt", "r");: This attempts to open the file named "nonexistent.txt" in read mode ("r"). If the file does not exist or cannot be opened for some reason, fopen will return NULL.

Error Handling

if (file == NULL) { ... }: This checks if the file pointer is NULL, indicating that fopen failed to open the file.

printf("Error opening file: %s\n", strerror(errno));: If file is NULL, this line prints an error message. strerror(errno) converts the error number stored in errno into a human-readable string that describes the error.

return 1;: This returns 1 from the main function, indicating that the program ended due to an error.

Closing the File

fclose(file);: If the file was successfully opened, this line closes the file. However, this line will only be executed if file is not NULL.

Normal Program Termination

return 0;: This returns 0 from the main function, indicating that the program terminated successfully.

Return Codes

Many functions in C return specific values to indicate success or failure. For example, the fopen function returns NULL if it fails to open a file.

#include <stdio.h>

int divide(int a, int b, int *result) {
    if (b == 0) {
        return -1; // Error code for division by zero
    }
    *result = a / b;
    return 0; // Success
}

int main() {
    int a = 10, b = 0;
    int result;
    
    if (divide(a, b, &result) != 0) {
        printf("Error: Division by zero\n");
    } else {
        printf("Result: %d\n", result);
    }
    
    return 0;
}
            

Header File

#include <stdio.h>: This header file includes the standard input and output library functions such as printf.

divide Function

int divide(int a, int b, int *result) { ... }: This is a function definition. The function takes three parameters: two integers a and b, and a pointer to an integer result. It returns an integer to indicate success or failure.

if (b == 0) { ... }: This checks if the divisor b is zero.

return -1;: If b is zero, the function returns -1 to indicate an error (division by zero).

*result = a / b;: If b is not zero, the function calculates the result of the division and stores it in the location pointed to by result.

return 0;: The function returns 0 to indicate that the operation was successful.

Main Function

int main() { ... }: The main function is the entry point of the program.

if (divide(a, b, &result) != 0) { ... }: This calls the divide function and checks the return value. If the return value is not 0, it indicates an error.

printf("Error: Division by zero\n");: If an error occurred, this line prints an error message.

printf("Result: %d\n", result);: If the division was successful, this line prints the result.

Normal Program Termination

return 0;: This returns 0 from the main function, indicating that the program terminated successfully.

Previous Next
Modern Footer