Preface
In C/C++ programming, the capture and processing of error messages is an important part of ensuring the robustness of the program. Errors are usually passed through the return value of the function or the global variable.errno
Come to express. To facilitate debugging and error handling, C/C++ provides a variety of functions and methods to obtain and output error information. The following are common methods and functions for C/C++ error handling:
1. errno and perror()
**
errno
**:errno
is a global variable that is set to an error code when a system call or library function fails.errno
is set by the operating system when an error occurs, and each error code represents a specific type of error.**
perror()
**:perror()
Used for printing basederrno
Error message of error code. It willerrno
The value of is converted into the corresponding error message and output. If a custom prefix string is provided, it will be output together.
Example:
#include <> #include <> #include <> int main() { FILE *file = fopen("non_existent_file.txt", "r"); if (!file) { perror("File opening failed"); } return 0; }
Output:
File opening failed: No such file or directory
In this example,perror()
Output a byerrno
The error message set is specifically "There is no such file or directory".
2. strerror()
- **
strerror()
**:strerror()
Functions are used to converterrno
The error code is converted into a readable string, and returns witherrno
Pointer to the corresponding error message. You can call it directly in the program to get a detailed error description.
Example:
#include <> #include <> #include <> int main() { FILE *file = fopen("non_existent_file.txt", "r"); if (!file) { printf("Error: %s\n", strerror(errno)); } return 0; }
Output:
Error: No such file or directory
3. The difference between perror() and strerror()
-
perror()
The error message will be automatically output to the standard error streamstderr
, and can be accompanied by a custom prefix. -
strerror()
Returns a pointer to the error message, and you can control the output by yourself in the program.
4. exit() and abort()
- **
exit()
**:exit()
Used to exit the program and return a specified status code. The returned status code can be used to represent the execution status of the program, usually0
Indicates success, non-zero value indicates an error.
Example:
#include <> #include <> int main() { if (some_error_condition) { fprintf(stderr, "An error occurred\n"); exit(1); // Exit with status 1 (error) } return 0; }
- **
abort()
**:abort()
Used to terminate the program immediately, usually used when the program encounters an unrecoverable error. Callabort()
After that, the program will be aborted immediately and an undefined error state will be returned.
Example:
#include <> #include <> int main() { if (some_fatal_error) { abort(); // Immediately terminate the program } return 0; }
5. assert()
- **
assert()
**:assert()
is a macro used during debugging to check whether the conditional expression is true. If the condition is not true, the program will output an error message and callabort()
Terminate the procedure.assert()
It is mainly used in the development and debugging stages and should not be used in production code.
Example:
#include <> #include <> int main() { int x = 5; assert(x == 10); // This will fail and abort the program return 0; }
6. setjmp() and longjmp()
- **
setjmp()
**:setjmp()
Used to set up a recovery point. If the program is called in subsequentlongjmp()
When jump to the recovery point,setjmp()
A non-zero value will be returned. - **
longjmp()
**:longjmp()
Used fromsetjmp()
Jump to a recovery point in the program where you are. It can be used for error handling, but is generally not recommended as a regular error handling mechanism.
Example:
#include <> #include <> jmp_buf env; void error_recovery() { printf("Error occurred, recovering...\n"); longjmp(env, 1); // Jump back to setjmp } int main() { if (setjmp(env) != 0) { printf("Recovered from error\n"); return 0; } error_recovery(); // Call this to simulate error return 0; }
7. strerror_r()
- **
strerror_r()
**:strerror_r()
It's thread-safestrerror()
version, it writes error information into the incoming buffer. becausestrerror()
Not thread-safe (it uses static buffers), so it is recommended to use it in multithreaded programs.strerror_r()
。
Example:
#include <> #include <> #include <> int main() { char buf[256]; errno = ENOENT; strerror_r(errno, buf, sizeof(buf)); printf("Error: %s\n", buf); return 0; }
8. Perror() and strerror() applicable scenarios
- **
perror()
**: Applicable to error messages that are output immediately when an error occurs, which are usually directly related to file operations, system calls, etc. - **
strerror()
**: Suitable for scenarios where reference or custom error message output is required in multiple places, especially when logging and debugging.
Common C/C++ error messages and functions
Common error messages
- **
ENOMEM
**: Insufficient memory - **
EAGAIN
**: Not available temporarily, usually means that resources are busy or blocked - **
EINVAL
**: Invalid parameter - **
EBADF
**: Invalid file descriptor - **
EIO
**: Input/output error - **
EPERM
**: Operation is not allowed - **
ENOENT
**: No file or directory
Common functions
- **
fopen()
、open()
**: File opening error, returnNULL
or-1
, need to useerrno
The judgment is incorrect. - **
socket()
**: Error when creating socket. - **
connect()
、send()
、recv()
**: Error in network programming.
Summarize
C/C++ provides a series of powerful error handling mechanisms, including global variableserrno
and functionsperror()
、strerror()
So wait to output and capture error information. By using these functions reasonably, errors in the program can be effectively captured and reported, helping developers locate problems in debugging and production environments.
This is the article about common methods and functions for handling C/C++ error information. For more related C/C++ error information, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!