Loading...

C essentialsFiles & System

Error handling: errno, perror & exit codes

8 min lesson

Next
  • Error handling is how your program detects, reports and reacts when something goes wrong, such as a failed file open or a bad argument.
  • It matters because real programs run in an unpredictable world: files may be missing, memory may run out, and users type unexpected input.
  • Think of error handling as the safety net under a trapeze artist: you hope never to use it, but it must be there and strong.
  • errno is a global integer set by many library functions to a code describing the last error.
  • perror prints a message with your text followed by a description of errno, like "open failed: No such file or directory".
  • strerror(errno) returns the same description as a string you can format yourself.
  • Exit codes are the integer returned from main or passed to exit; 0 means success and nonzero means failure.
  • The computer records the exit code so the shell or a calling program can check whether the program succeeded.
  • The syntax is: check the return value, then use perror or strerror to report, and return a nonzero code from main.
  • A realistic use: opening a configuration file, reporting why it failed, and exiting with status 1 so scripts can detect the failure.
  • A surprising detail: errno is only meaningful right after a failed call; another call can overwrite it, so save it if you need it later.
  • The example program tries to open a file that does not exist, prints an error with perror, and returns a failure code.
Keep in mind
  • Check the return value of every function that can fail.
  • Use perror or strerror to turn errno into a readable message.
  • Return 0 for success and nonzero for failure so scripts can react.
  • Read errno immediately after a failure; it can change quickly.
  • Good error handling is what makes programs trustworthy. Well done!
main.c
#include <stdio.h>
#include <errno.h>
#include <string.h>

int main(void) {
    // Try to open a file that does not exist
    const char *path = "missing.txt";
    FILE *f = fopen(path, "r");

    // fopen returns NULL on failure; check before using f
    if (f == NULL) {
        // perror prints our message plus the errno description
        perror("fopen failed");
        // Also print the numeric error code for reference
        printf("errno = %d\n", errno);
        // Return a nonzero exit code so scripts know it failed
        return 1;
    }

    // This line would run only if the file existed
    printf("Opened %s\n", path);
    fclose(f);
    return 0;
}

What happens: fopen failed: No such file or directory errno = 2

Breaking it down

fopen call

FILE *f = fopen(path, "r");

Tries to open the file for reading. On failure it returns NULL and sets errno.

NULL check

if (f == NULL)

Detects the failure before using f. Using a NULL FILE * would crash the program.

perror

perror("fopen failed");

Prints your text followed by a colon and the errno description, giving a readable error.

errno print

printf("errno = %d", errno);

Shows the numeric code, useful for logging or looking up in documentation.

Exit code

return 1;

Tells the shell the program failed. Scripts can check $? to see this code.

Common errno values

CodeNameMeaning
2ENOENTNo such file or directory
13EACCESPermission denied
12ENOMEMOut of memory
17EEXISTFile already exists
22EINVALInvalid argument

A helpful analogy

Error handling is like a safety net under a trapeze artist. You hope the trick succeeds every time, but the net must be there and strong. errno is the note that says what went wrong, perror reads the note aloud, and the exit code tells the audience whether the show succeeded.

Nesting rules

  • 1.Check the return value of every function that can fail before using its result.
  • 2.Read errno immediately after the failure; later calls may overwrite it.
  • 3.Return 0 from main for success and a nonzero value for failure.
  • 4.Use perror for quick messages and strerror when you need to format the message yourself.

Common mistakes

Ignoring the return value of fopen

Avoid

FILE *f = fopen("x", "r"); fgetc(f); // crash if NULL

Use instead

if (!(f = fopen("x", "r"))) { perror("fopen"); return 1; }

If fopen fails it returns NULL. Using NULL as a FILE * is undefined behavior and usually crashes.

Reading errno too late

Avoid

int r = func(); printf("x"); if (errno) ...

Use instead

int r = func(); if (r == -1) perror("func");

Other calls can overwrite errno. Check the return value and read errno immediately after the failing call.

Returning 0 on failure

Avoid

if (!f) return 0; // success? no

Use instead

if (!f) return 1;

Scripts check the exit code. Returning 0 tells them the program succeeded, hiding the failure.

Quick tips

  • •Run the program and then type echo $? in the shell to see the exit code.
  • •Use strerror(errno) to build a custom error message with printf.
  • •Log the file name and the error together so debugging is easier.
  • •Try changing the path to an existing file to see the success path.
  • •Check man errno for the full list of error codes.
Previous
Next