C ErrorsLesson 47Free preview
C Error Handling
This lesson is part of C · All levels
Summary
C has no exception mechanism, so error handling is generally done through return values and global variables errno. Many standard functions send a failure marker such as NULL or −1, and then the programmer checks errno to find the cause. Consistent patterns, such as 0 for success and non-zero code for failure, make code easier for the caller to handle.
Key points
- Errno is set by the library function when the operation fails, and must be checked immediately after the function is called.
- The perror displays the corresponding explanatory message with the errno, whereas the strerror returns it as a string.
- General convention: 0 means success and non-zero means failure.
- Functions such as strtol keep the parsing stop position in the endptr so that the input can be validated.
- Provide clear handling routes such as message, fallback, or memory clearance when the operation could fail.
Full lesson
Code examples and quizzes
Full lessons, code examples, and quizzes are available to subscribers. 5 questions.