Error Handling in C | C में एरर हैंडलिंग की पूरी गाइड
क्या आपने कभी C प्रोग्राम चलाया और अचानक “Segmentation Fault” देख लिया? या file open नहीं हुई, लेकिन program silently बंद हो गया?
यही वह जगह है जहाँ Error Handling in C की जरूरत पड़ती है। C language powerful है, लेकिन इसमें automatic exception handling नहीं होती जैसे Java या Python में होती है। इसलिए developer को खुद C में एरर हैंडलिंग manage करनी पड़ती है।
इस लेख में हम सीखेंगे:
- ✔ Error Handling in C क्या है
- ✔ errno, perror(), strerror() का उपयोग
- ✔ return codes और exit() कैसे काम करते हैं
- ✔ practical examples
- ✔ best practices और debugging tips
📌 Table of Contents
- Error Handling in C क्या है?
- C में Errors के प्रकार
- errno और perror() का उपयोग
- Return Codes & exit()
- Best Practices
- Real World Example
- FAQs
Error Handling in C क्या है?
Error Handling in C का मतलब है program के दौरान आने वाली समस्याओं को पहचानना (detect करना) और उन्हें सुरक्षित तरीके से handle करना।
क्यों जरूरी है?
- Program crash से बचाने के लिए
- Data corruption रोकने के लिए
- User को meaningful message देने के लिए
- System stability बनाए रखने के लिए
सरल उदाहरण: अगर आप bank ATM बना रहे हैं और withdrawal error handle नहीं किया, तो account balance गलत हो सकता है।
C में Errors के प्रकार
1️⃣ Compile-Time Errors
Syntax mistakes जैसे semicolon भूल जाना। Compiler इन्हें पकड़ लेता है।
2️⃣ Run-Time Errors
Program चलते समय error आना जैसे divide by zero।
3️⃣ Logical Errors
Program चलता है लेकिन output गलत आता है।
C में एरर हैंडलिंग मुख्यतः run-time errors को manage करने पर केंद्रित होती है।
errno, perror() और strerror() का उपयोग
🔹 errno क्या है?
errno एक global variable है जो system call fail होने पर error code store करता है।
#include <errno.h>
#include <stdio.h>
FILE *file = fopen("data.txt", "r");
if (file == NULL) {
printf("Error number: %d\n", errno);
}
🔹 perror() Function
perror() error message print करता है।
if (file == NULL) {
perror("File opening failed");
}
🔹 strerror()
strerror() error number को readable string में बदलता है।
printf("%s\n", strerror(errno));
ये तीनों tools Error Handling in C का foundation हैं।
Return Codes और exit() Function
C में exception नहीं होते, इसलिए functions return value से error indicate करते हैं।
🔹 Return Codes
- 0 → Success
- Non-zero → Error
🔹 exit() Function
#include <stdlib.h>
if (file == NULL) {
exit(EXIT_FAILURE);
}
EXIT_SUCCESS और EXIT_FAILURE predefined macros हैं।
यह तरीका production-level systems में standard practice है।
C में एरर हैंडलिंग की Best Practices
✔ 1. हर Function Call Check करें
कोई भी system call blindly use न करें।
✔ 2. Meaningful Error Messages दें
User को समझ आए ऐसा message दें।
✔ 3. Resource Cleanup करें
Memory leak से बचें।
✔ 4. Logging करें
Production environment में logging अनिवार्य है।
✔ 5. assert() का सही उपयोग
Debugging के दौरान assert() helpful होता है।
Real World Example – File Processing Program
मान लीजिए आप CSV file पढ़ रहे हैं। Proper Error Handling in C के बिना program crash हो सकता है।
FILE *fp = fopen("data.csv", "r");
if (fp == NULL) {
perror("Unable to open file");
return 1;
}
Signal Handling in C
C programs runtime में critical errors जैसे segmentation fault या user interrupt handle करने के लिए signal handling का उपयोग कर सकते हैं। यह traditional return code based error handling का advanced extension है।
Basic Example:
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
void handle_signal(int sig) {
printf("Signal %d received. Exiting safely.\n", sig);
exit(EXIT_FAILURE);
}
int main() {
signal(SIGINT, handle_signal); // Ctrl+C interrupt handle
while(1) {
printf("Running...\n");
sleep(1);
}
return 0;
}
यह code Ctrl+C दबाने पर program crash के बिना safely terminate होता है।
Custom Error Macros & Enumerations
Standard errno के अलावा, large projects में developers अक्सर custom error codes और macros बनाते हैं ताकि errors को standardized और readable बनाया जा सके।
#define ERR_SUCCESS 0
#define ERR_FILE_OPEN 1
#define ERR_OUT_OF_MEM 2
#define CHECK_ERR(cond, code) \
do { if (!(cond)) return (code); } while (0)
int read_file(const char *filename) {
FILE *fp = fopen(filename, "r");
CHECK_ERR(fp != NULL, ERR_FILE_OPEN);
// file processing
fclose(fp);
return ERR_SUCCESS;
}
Macro CHECK_ERR automatically error return handle करता है।
Logging Frameworks & Error Tracing
Error messages सिर्फ print करने से काम नहीं चलता। Production code में logs maintain करना critical है।
#include <stdio.h>
void log_error(const char *module, const char *msg) {
fprintf(stderr, "[ERROR] %s: %s\n", module, msg);
}
int main() {
FILE *fp = fopen("data.txt", "r");
if (!fp) {
log_error("FileModule", "Failed to open data.txt");
return 1;
}
fclose(fp);
return 0;
}
यह structured logging approach debugging और production monitoring में मदद करता है।
Structured Error Data Types
Complex programs में सिर्फ integer error codes पर्याप्त नहीं होते। इस लिए developers often use error structs:
typedef struct {
int code;
const char *msg;
} error_t;
error_t make_error(int code, const char *msg) {
error_t err = {code, msg};
return err;
}
int main() {
error_t err = make_error(1, "File not found");
printf("Error %d: %s\n", err.code, err.msg);
return 0;
}
यह approach error context और debugging को बेहतर बनाता है।
Resource Cleanup Patterns
C में error path में memory leak और resource misuse रोकने के लिए cleanup pattern use करना जरूरी है।
int process_file(const char *filename) {
FILE *fp = fopen(filename, "r");
char *buffer = malloc(1024);
if (!fp || !buffer) {
goto cleanup;
}
// file processing code
cleanup:
if (fp) fclose(fp);
if (buffer) free(buffer);
return 0;
}
goto cleanup approach resource management को error-safe बनाता है।
setjmp() / longjmp() – Exception-like Flow in C
C में traditional exceptions नहीं होते। setjmp() और longjmp() का उपयोग करके try-catch style flow emulate किया जा सकता है।
#include <setjmp.h>
#include <stdio.h>
jmp_buf jump_buffer;
void risky_operation() {
printf("Something risky...\n");
longjmp(jump_buffer, 1); // jump back to main
}
int main() {
if (setjmp(jump_buffer) == 0) {
risky_operation();
} else {
printf("Recovered from error!\n");
}
return 0;
}
यह advanced technique program को crash होने से बचाकर recover करने में मदद करती है।
अब आपका program safe है।
FAQs – Error Handling in C
1. C में exception handling क्यों नहीं होती?
C low-level language है, इसलिए automatic exception mechanism नहीं है।
2. errno कब set होता है?
जब system call fail होता है।
3. perror() और strerror() में अंतर?
perror() सीधे print करता है, strerror() string return करता है।
4. EXIT_FAILURE का मतलब?
Program abnormal तरीके से terminate हुआ।
5. क्या हर function के बाद error check जरूरी है?
हाँ, खासकर file, memory और network operations में।
Post a Comment
Blogger FacebookYour Comment Will be Show after Approval , Thanks