Ad space (banner)
๐Ÿ”งC Lessons
Lesson 25 / 68

Custom Errors (Categorizing with Error Codes)

This lesson covers expressing your own error categories in C using error codes, so you can distinguish between types of errors more specifically. It's for anyone searching "C error code categorization."

C has no exception classes, but defining error codes with enum makes it easier to distinguish between error types. Think of it like preparing a named constant for each category of error.

The example defines error types with typedef enum { ERR_NONE, ERR_INVALID_AGE } ErrorCode;, and the check_age() function returns ERR_INVALID_AGE when the age is negative. The caller can tell what went wrong by looking at the returned error code.

A common early mistake is not realizing an error code alone struggles to convey detailed information (like a message). If you need more detail, you'd need a technique like bundling error info into a struct instead.

In real projects, distinguishing between something like "an invalid input" error and "a network failure" error lets you write the appropriate response for each in code.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run C directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)