Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING HTML & CSS BASH RUST TOOLS

C Tutorial

C HOME C Intro C Get Started C Syntax C Output C Comments C Variables C Data Types C Type Conversion C Constants C Operators C Booleans C If...Else C Switch C While Loop C For Loop C Break/Continue C Arrays C Strings C User Input C Memory Address C Pointers

C Functions

C Functions C Function Parameters C Pass By Reference C Scope C Function Declaration C Functions Challenge C Math Functions C Inline Functions C Recursion C Function Pointers

C Files

C Create Files C Write To Files C Read Files

C Structures

C Structures C Structs Challenge C Nested Structures C Arrays of Structs C Structs & Pointers C Unions C typedef C Struct Padding

C Enums

C Enums

C Memory

C Memory Management C Allocate Memory C Access Memory C Reallocate Memory C Deallocate Memory C Structs and Memory C Memory Example C Memory Mistakes

C Errors

C Errors C Error Challenge C Debugging C NULL C Error Handling C Input Validation

C Problem Solving

C Problem Solving C Build the Logic C Edge Cases & Errors C Test Cases

C More

C Date C Random Numbers C Macros C Organize Code C Storage Classes C Bitwise Operators C Fixed-width Integers C Command-Line Args

C DSA

C DSA Intro C Searching C Sorting C Stacks C Queues C Linked Lists C Trees C Hash Tables C Big O

C Projects

C Projects

C Cert

C Certificate

C Reference

C Reference C Keywords C <stdio.h> C <stdlib.h> C <string.h> C <math.h> C <ctype.h> C <time.h>

C Examples

C Examples C Real-Life Examples C Exercises C Quiz C Code Challenges C Practice Problems C Compiler C Syllabus C Study Plan C Interview Q&A

C Error Handling


Share

Error Handling in C

Error handling lets you detect and respond to problems in your program, like a file that can't be opened or memory that can't be allocated, so your program doesn't crash or behave unexpectedly.

Unlike some languages, C does not have built-in exception handling (like try/catch). Instead, C uses return values, global error codes, and helper functions like perror() and strerror().


Using Return Values

In the previous chapter, you learned that functions like fopen() return NULL when something goes wrong.

You can check for NULL using an if statement to detect and handle errors before your program crashes.

In the example below, we try to open a file that does not exist. Since fopen() fails, it returns NULL and we print an error message:

Example: fopen() fails

#include <stdio.h>

int main() {
  FILE *fptr = fopen("nothing.txt", "r");

  if (fptr == NULL) {
    printf("Error opening file.\n");
    return 1;
  }

  fclose(fptr);
  return 0;
}

Result:

Error opening file.
Try it Yourself »

Note: In the Read Files chapter, fclose() was inside an if...else statement, so it was only called when the file was opened. Here, we do not need the else: if fopen() fails, return 1 stops the program before it reaches fclose(). You will learn more about return values in the section below.


Return Error Codes From Your Own Functions

You can use the same idea in your own functions: return a value that tells the caller if something went wrong. A common way is to return 0 for success, and another number (like -1) for an error.

This function divides two numbers. If the second number is 0, it returns -1. Otherwise, it stores the result through a pointer (see Pass By Reference) and returns 0:

Example: Return an error code

#include <stdio.h>

// Returns 0 if everything is OK, and -1 if b is 0
int divide(int a, int b, int *result) {
  if (b == 0) {
    return -1;
  }
  *result = a / b;
  return 0;
}

int main() {
  int result;

  if (divide(10, 0, &result) != 0) {
    printf("Error: Division by zero!\n");
    return 1;
  }

  printf("Result: %d\n", result);
  return 0;
}

Result:

Error: Division by zero!
Try it Yourself »

The caller checks the returned value, and only uses result if the function returned 0.


Get More Details

If you want more details about what went wrong, you can use the perror() function.

It prints a custom error message followed by a description of the last error that occurred:

Example: perror() with fopen()

#include <stdio.h>

int main() {
  FILE *f = fopen("nothing.txt", "r");

  if (f == NULL) {
    perror("Error opening file");
    return 1;
  }

  fclose(f);
  return 0;
}

Result:

Error opening file: No such file or directory
Try it Yourself »


Using strerror() and errno

errno is a global variable that stores the error code from the last failed operation. You can include <errno.h> to access it, and strerror(errno) will convert the error code into a readable message:

Example: strerror()

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

int main() {
  FILE *f = fopen("nothing.txt", "r");

  if (f == NULL) {
    printf("Error: %s\n", strerror(errno));
    return 1;
  }

  fclose(f);
  return 0;
}

Result:

Error: No such file or directory
Try it Yourself »

Note: errno is only set when something goes wrong, and it keeps its value until the next error. That is why you should only check it right after a function has failed (like when fopen() returns NULL).

Common Error Codes

Error constants are defined in <errno.h>. You can compare errno to them to detect specific issues:

Error CodeMeaning
ENOENTNo such file or directory
EACCESPermission denied
ENOMEMNot enough memory
EINVALInvalid argument

Example: Custom message for ENOENT

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

int main() {
  FILE *f = fopen("nothing.txt", "r");

  if (f == NULL) {
    if (errno == ENOENT) {
      printf("The file was not found.\n");
    } else {
      printf("Some other file error occurred.\n");
    }
    return 1;
  }

  fclose(f);
  return 0;
}

Result:

The file was not found.
Try it Yourself »

Using exit() to Stop the Program

If you want to stop the program immediately when an error occurs, you can use exit(). It lets you return a status code to the operating system.

Exit codes help signal whether the program finished successfully or with an error, like:

  • 0 means success
  • Non-zero values (like 1 or EXIT_FAILURE) indicate errors

Example: Using exit() on error

#include <stdio.h>
#include <stdlib.h>

int main() {
  FILE *f = fopen("nothing.txt", "r");

  if (f == NULL) {
    printf("Failed to open file.\n");
    exit(1);
  }

  fclose(f);
  return 0;
}

Result:

Failed to open file.
Try it Yourself »

Note: In main(), exit(1) does the same as return 1. The difference is that exit() stops the whole program from any function, while return only leaves the function it is in.

Common Exit Status Codes

CodeMeaning
0Success - the program completed normally
1Error - something went wrong
EXIT_SUCCESSSame as 0 (defined in <stdlib.h>)
EXIT_FAILURESame as a non-zero error code (also in <stdlib.h>)

Tip: You can use EXIT_SUCCESS and EXIT_FAILURE instead of numbers to make your code more readable.

Example: Using EXIT_FAILURE and EXIT_SUCCESS

#include <stdio.h>
#include <stdlib.h>

int main() {
  FILE *f = fopen("nothing.txt", "r");

  if (f == NULL) {
    perror("Could not open nothing.txt");
    exit(EXIT_FAILURE); // More readable than exit(1)
  }

  fclose(f);
  return EXIT_SUCCESS;
}

Result:

Could not open nothing.txt: No such file or directory
Try it Yourself »

Summary

  • Many C functions return NULL when something goes wrong
  • Your own functions can return an error code (like -1) to tell the caller that something went wrong
  • Use perror() to print a message about the error
  • Use strerror(errno) to get the error message as a string
  • errno stores the error code from the last failed action
  • You can compare errno to values like ENOENT (file not found) or ENOMEM (not enough memory)
  • Use exit() to stop the program early if there's an error

Tip: Always check for errors after file operations, memory allocation, and system calls. Ignoring errors can lead to unexpected behavior or crashes.




Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.