Creating Custom Error Messages in C
Creating Custom Error Messages in C
C programming language provides a built-in error handling mechanism that lets you identify and respond to errors during program execution. However, sometimes, the in-built error messages are not sufficient to explain the problem clearly. In such cases, creating custom error messages can provide a more descriptive and user-friendly way to notify about errors.
Basics of Error Handling in C
In C, error handling involves the use of several library functions such as perror()
, strerror()
, and errno
. Here's a brief description of these functions:
perror()
: This function displays a string you pass to it, followed by a colon and a space, and then a textual representation of the current errno value.strerror()
: This function returns a pointer to the textual representation of the current errno value.errno
: This is a preprocessor macro that includes a system-related error number.
Creating Custom Error Messages
To create a custom error message in C, you need to use the printf()
function along with the strerror()
function or errno
variable.
Here's an example of using strerror()
:
#include <stdio.h>
#include <string.h>
#include <errno.h>
int main() {
FILE *filePtr;
filePtr = fopen("non_existent_file.txt", "r");
if (filePtr == NULL) {
printf("Error: %s\n", strerror(errno));
return 1;
}
fclose(filePtr);
return 0;
}
In this example, if the file does not exist, the fopen()
function returns NULL
and sets errno
to a value that represents the error. The strerror()
function then converts this error number into a human-readable string.
You can also create custom error messages using the perror()
function. Here's how you can do this:
#include <stdio.h>
int main() {
FILE *filePtr;
filePtr = fopen("non_existent_file.txt", "r");
if (filePtr == NULL) {
perror("Error");
return 1;
}
fclose(filePtr);
return 0;
}
In this example, if the file does not exist, the perror()
function will print the string "Error" followed by a colon, a space, and then a textual representation of the error.
Conclusion
In this tutorial, you learned how to create custom error messages in C. While the built-in error messages provided by C are useful, creating custom error messages can provide more clarity and help make your program more user-friendly. Always remember to provide clear and concise error messages that help the user understand what went wrong.