Movatterモバイル変換


[0]ホーム

URL:


Menu
×
See More 
Sign In
+1 Get Certified Upgrade Teachers Spaces Get Certified Upgrade Teachers Spaces
   ❮   
     ❯   

C Tutorial

C HOMEC IntroC Get StartedC SyntaxC OutputC CommentsC VariablesC Data TypesC Type ConversionC ConstantsC OperatorsC BooleansC If...ElseC SwitchC While LoopC For LoopC Break/ContinueC ArraysC StringsC User InputC Memory AddressC Pointers

C Functions

C FunctionsC Function ParametersC ScopeC Function DeclarationC Math FunctionsC Inline FunctionsC RecursionC Function Pointers

C Files

C Create FilesC Write To FilesC Read Files

C Structures

C StructuresC Nested StructuresC Structs & PointersC UnionsC typedefC Struct Padding

C Enums

C Enums

C Memory

C Memory Management

C Errors

C ErrorsC DebuggingC NULLC Error HandlingC Input Validation

C More

C DateC Random NumbersC MacrosC Organize CodeC Storage ClassesC Bitwise OperatorsC Fixed-width Integers

C Projects

C Projects

C Reference

C ReferenceC KeywordsC <stdio.h>C <stdlib.h>C <string.h>C <math.h>C <ctype.h>C <time.h>

C Examples

C ExamplesC Real-Life ExamplesC ExercisesC QuizC CompilerC SyllabusC Study PlanC Interview Q&AC Certificate

CError Handling


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 (liketry/catch). Instead, C uses return values, global error codes, and helper functions likeperror() andstrerror().


Using Return Values

In the previous chapter, you learned that functions likefopen() returnNULL when something goes wrong.

You can check forNULL using anif statement to detect and handle errors before your program crashes.

In the example below, we try to open a file that does not exist. Sincefopen() fails, it returnsNULL 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.

Get More Details

If you want more details about what went wrong, you can use theperror() 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

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, andstrerror(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

Common Error Codes

Error constants are defined in<errno.h>. You can compareerrno 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.

Using exit() to Stop the Program

If you want to stop the program immediately when an error occurs, you can useexit(). 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 (like1 orEXIT_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.

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 useEXIT_SUCCESS andEXIT_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

Summary

  • Many C functions returnNULL when something goes wrong
  • Useperror() to print a message about the error
  • Usestrerror(errno) to get the error message as a string
  • errno stores the error code from the last failed action
  • You can compareerrno to values likeENOENT (file not found) orENOMEM (not enough memory)
  • Useexit() 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.



×

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 ourterms of use,cookies andprivacy policy.

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


[8]ページ先頭

©2009-2025 Movatter.jp