give me a best practice handle error in c
- User
give me a best practice handle error in c
Assistant
Here's a best practice approach for error handling in C:
#include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> // Error handling macro #define HANDLE_ERROR(msg) do { \ fprintf(stderr, "%s failed: %s\n", msg, strerror(errno)); \ exit(EXIT_FAILURE); \ } while (0) // Function that demonstrates error handling int safe_file_operation(const char *filename) { FILE *file = fopen(filename, "r"); if (file == NULL) { // Handle specific error cases differently if (errno == ENOENT) { fprintf(stderr, "File '%s' does not exist\n", filename); return -1; } else { HANDLE_ERROR("File opening"); } } // Use the file... // Clean up resources even if an error occurs if (fclose(file) != 0) { HANDLE_ERROR("File closing"); } return 0; } int main() { int result = safe_file_operation("nonexistent.txt"); if (result != 0) { printf("Handled the error gracefully\n"); } return 0; }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.