← Back to C Course | Chapter 12: Advanced Topics | Lesson 16 of 20

C में Error Handling

Error handling यह check करना है कि चीज़ें काम कीं या नहीं और योजना बनाना कि न करने पर क्या किया जाए, एक spare tire रखने जैसा। यह एक problem को सब कुछ बर्बाद करने से रोकता है।
Syntax
c
if (function_name(arguments) == error_value) {
  // handle the failure
}

if (divisor == 0) {
  // avoid dividing by zero
}

Return Values Check करना

Standard library functions अपने return value से failure signal करते हैं — अक्सर एक pointer-returning function के लिए NULL या एक integer-returning वाले के लिए -1 — इसलिए call के तुरंत बाद वह return value check करना C में सबसे basic और सबसे ज़्यादा skip होने वाली error-handling habit है।

उदाहरण: Checking Return Values

c
// Include standard input/output (printf, scanf)
#include <stdio.h>
// Program execution starts in main()
int main() {
	FILE *fp = fopen("nonexistent.txt", "r");
	// Check whether fp == NULL
	if (fp == NULL) {
		// Print formatted text to the screen
		printf("Failed to open");
		// Send 1 back to the caller
		return 1;
	}
	fclose(fp);
	// Return 0 to signal that the program finished successfully
	return 0;
}

Division by Zero Handle करना

C division by zero के लिए कोई automatic check नहीं करता, इसलिए एक integer को एक variable से divide करना जो zero निकले program crash करता है (या, floating-point division के लिए, inf या nan produce करता है) एक catchable exception उठाने की बजाय।

Divide करने से पहले एक plain if से एक divisor validate करना इकलौता reliable defense है।

उदाहरण: Handling Division by Zero

c
// Include standard input/output (printf, scanf)
#include <stdio.h>
// Program execution starts in main()
int main() {
	int a = 10, b = 0;
	// Check whether b == 0
	if (b == 0) {
		// Print formatted text to the screen
		printf("Cannot divide by zero");
	} else {
		// Print formatted text to the screen
		printf("%d", a / b);
	}
	// Return 0 to signal that the program finished successfully
	return 0;
}

Allocation Failures Handle करना

जब dynamic memory खत्म हो जाए, malloc() और इसके relatives एक valid pointer की बजाय NULL return करते हैं, और पहले check किए बिना उस NULL pointer के जरिए लिखना program crash कर देता है।

हमेशा इसकी चाहिए होने वाली memory इस्तेमाल करने से पहले एक allocation call का return value test करें।

उदाहरण: Handling Allocation Failures

c
// Include standard input/output (printf, scanf)
#include <stdio.h>
// Include general utilities (malloc, free, exit)
#include <stdlib.h>
// Program execution starts in main()
int main() {
	// Allocate memory on the heap
	int *ptr = malloc(sizeof(int));
	// Check whether ptr == NULL
	if (ptr == NULL) {
		// Print formatted text to the screen
		printf("Allocation failed");
		// Send 1 back to the caller
		return 1;
	}
	*ptr = 5;
	// Print formatted text to the screen
	printf("%d", *ptr);
	free(ptr);
	return 0;
}

Fallback Defaults Set करना

जब एक operation plausibly fail हो सकता है लेकिन program अभी भी progress कर सकता है, एक sensible default value पर fall back करना (garbage या एक uninitialized value propagate करने की बजाय) execution को stable रखता है इसकी बजाय कि एक bad reading आगे सब कुछ corrupt कर दे।

उदाहरण: Setting Fallback Defaults

c
// Include standard input/output (printf, scanf)
#include <stdio.h>
// Program execution starts in main()
int main() {
	// Declare userInput and set it to -1
	int userInput = -1;
	int value = (userInput < 0) ? 0 : userInput;
	// Print formatted text to the screen
	printf("%d", value);
	// Return 0 to signal that the program finished successfully
	return 0;
}

Graceful Termination

जब एक error truly recover नहीं हो सकती, एक non-zero status code के साथ cleanly exit करना (आमतौर पर exit(1) या main से एक non-zero return के जरिए) किसी भी calling shell script या parent process को बताता है कि कुछ गलत हुआ, जो एक program का exit status check करने वाली automation के लिए मायने रखता है।

उदाहरण: Graceful Termination

c
// Include standard input/output (printf, scanf)
#include <stdio.h>
// Include general utilities (malloc, free, exit)
#include <stdlib.h>
// Program execution starts in main()
int main() {
	// Declare criticalError and set it to 1
	int criticalError = 1;
	// Check whether criticalError
	if (criticalError) {
		// Print formatted text to the screen
		printf("Unrecoverable error");
		exit(1);
	}
	// Return 0 to signal that the program finished successfully
	return 0;
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. fopen और malloc जैसे functions के return values ignore करना।
  2. pointer इस्तेमाल करने से पहले malloc का result check न करना।
  3. divide करने से पहले एक zero divisor check न करना, जो integers के लिए undefined behavior है।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.