🔴 Advanced  ·  Lesson 45

Error Handling in C

Error Handling

Error Handling

C does not have exceptions like some modern languages. We handle errors using return values, NULL, errno, perror() and careful checking.

Return Codes

C Language
#include <stdio.h>

int divide(int a, int b, int *result) {
    if(b == 0) return 0;   // failure
    *result = a / b;
    return 1;              // success
}

int main() {
    int ans;
    if(divide(10, 0, &ans))
        printf("Result = %d", ans);
    else
        printf("Error: divide by zero");
    return 0;
}

errno and perror

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

int main() {
    FILE *fp = fopen("missing.txt", "r");
    if(fp == NULL) {
        perror("File error");
        printf("errno = %d\n", errno);
        printf("Message = %s", strerror(errno));
        return 1;
    }
    fclose(fp);
    return 0;
}

File Error Handling

C Language
FILE *fp = fopen("data.txt", "r");
if(fp == NULL) {
    printf("Unable to open file");
    return 1;
}

Memory Error Handling

C Language
int *arr = malloc(n * sizeof(int));
if(arr == NULL) {
    printf("Memory allocation failed");
    return 1;
}

Summary

  • Check return values of functions
  • Check NULL for file and memory operations
  • Use perror() for system error messages
  • Use clear return codes for your own functions
  • Handle errors early to avoid crashes

Error Handling

C में exceptions नहीं होते। Errors को return values, NULL, errno और perror() से handle किया जाता है।

Return Codes

C Language
if(b == 0) return 0;  // error
return 1;             // success

errno और perror

C Language
FILE *fp = fopen("missing.txt", "r");
if(fp == NULL) {
    perror("File error");
    return 1;
}

File Error

C Language
if(fp == NULL) {
    printf("Unable to open file");
    return 1;
}

Memory Error

C Language
int *arr = malloc(n * sizeof(int));
if(arr == NULL) {
    printf("Memory allocation failed");
    return 1;
}

सारांश

  • Function return values check करें
  • File और memory के लिए NULL check करें
  • perror system error message देता है
  • अपने functions में clear return codes रखें
  • Error को समय पर handle करें
← Back to C Tutorial