← Back to C++ Course | Chapter 12: Exception Handling | Lesson 4 of 5

C++ के Custom Exceptions

एक custom exception एक error type है जो आप खुद अपने program में fit होने वाले एक नाम के साथ बनाते हैं, अपने खुद के playground के लिए एक special warning sign की तरह। यह problems को समझना आसान बनाता है।
Syntax
cpp
class CustomException {
public:
  std::string message;
  CustomException(std::string msg) : message(msg) {}
};

try {
  throw CustomException("text");
} catch (CustomException &e) {
  // e.message
}

Custom Exceptions क्यों?

Standard library में built-in exceptions useful हैं लेकिन generic हैं; अपने खुद के exception types define करना आपको error categories बनाने देता है जो आपके application की खुद की business logic पर precisely map हों, जो debugging और targeted error handling को कहीं ज़्यादा clean बनाता है।

उदाहरण: Why Custom Exceptions?

cpp
// Include std::cout and std::cin
#include <iostream>
// Include std::string
#include <string>

// Define the type InvalidAgeError
class InvalidAgeError {
// Members below can be accessed from outside the class
public:
	std::string message = "Age cannot be negative";
};

// Program execution starts in main()
int main() {
	// Try code that might throw an exception
	try {
		// Throw an exception to signal an error
		throw InvalidAgeError();
	// Handle the exception if one was thrown
	} catch (InvalidAgeError &e) {
		std::cout << e.message << std::endl;
	}
	return 0;
}

एक Basic Exception Class बनाना

इसके simplest पर, एक custom exception class बस एक ordinary class है जो भी data और methods आप decide करें कि इसे चाहिए — आप इसके instances throw करते हैं और उन्हें उस specific class type से catch करते हैं, किसी भी standard exception की तरह।

उदाहरण: Creating a Basic Exception Class

cpp
// Include std::cout and std::cin
#include <iostream>
// Include std::string
#include <string>

// Define the type MyException
class MyException {
// Members below can be accessed from outside the class
public:
	std::string message;
	MyException(std::string msg) : message(msg) {}
};

// Program execution starts in main()
int main() {
	// Try code that might throw an exception
	try {
		// Throw an exception to signal an error
		throw MyException("Something broke");
	// Handle the exception if one was thrown
	} catch (MyException &e) {
		std::cout << e.message << std::endl;
	}
	return 0;
}

std::exception से Inherit करना

एक custom exception बनाने का professional तरीका std::exception से inherit करना और इसकी virtual what() method override करना है।

ऐसा करना std::exception के लिए लिखे generic catch blocks को आपकी specific type के बारे में जाने बिना आपके custom exceptions भी handle करने देता है।

उदाहरण: Inheriting from std::exception

cpp
// Include std::cout and std::cin
#include <iostream>
#include <exception>

// Define the type MyException
class MyException : public std::exception {
// Members below can be accessed from outside the class
public:
	const char *what() const noexcept override {
		// Send "Custom exception occurred" back to the caller
		return "Custom exception occurred";
	}
};

// Program execution starts in main()
int main() {
	// Try code that might throw an exception
	try {
		// Throw an exception to signal an error
		throw MyException();
	// Handle the exception if one was thrown
	} catch (std::exception &e) {
		std::cout << e.what() << std::endl;
	}
	return 0;
}

Custom Data के साथ Custom Exceptions

क्योंकि आपका exception एक real class है, यह failure के साथ custom member data carry कर सकता है — एक error code, एक file path, एक timestamp — इसे catch करने वाले code को अकेले एक bare error message से कहीं ज़्यादा richer information देते हुए।

उदाहरण: Custom Exceptions with Custom Data

cpp
// Include std::cout and std::cin
#include <iostream>
#include <exception>

// Define the type ValidationError
class ValidationError : public std::exception {
// Members below can be accessed from outside the class
public:
	int errorCode;
	ValidationError(int code) : errorCode(code) {}
	const char *what() const noexcept override {
		// Send "Validation failed" back to the caller
		return "Validation failed";
	}
};

// Program execution starts in main()
int main() {
	// Try code that might throw an exception
	try {
		// Throw an exception to signal an error
		throw ValidationError(422);
	// Handle the exception if one was thrown
	} catch (ValidationError &e) {
		std::cout << e.what() << " code=" << e.errorCode << std::endl;
	}
	return 0;
}

Validation में Practical Usage

Practice में, custom exceptions आमतौर पर validation logic या system-level operations के अंदर से throw होते हैं, जहाँ वे stack में आगे किसी भी code को exactly बताते हैं कि क्या गलत हुआ जो यह decide करने के लिए responsible है कि कैसे respond करना है।

उदाहरण: Practical Usage in Validation

cpp
// Include std::cout and std::cin
#include <iostream>
#include <exception>

// Define the type InvalidAgeError
class InvalidAgeError : public std::exception {
// Members below can be accessed from outside the class
public:
	const char *what() const noexcept override {
		// Send "Age must be non-negative" back to the caller
		return "Age must be non-negative";
	}
};

void checkAge(int age) {
	if (age < 0) throw InvalidAgeError();
}

// Program execution starts in main()
int main() {
	// Try code that might throw an exception
	try {
		checkAge(-5);
	// Handle the exception if one was thrown
	} catch (std::exception &e) {
		// Print to the console with cout
		std::cout << e.what() << std::endl;
	}
	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. std::exception से inherit न करना, ताकि catch (std::exception&) इसे catch न कर सके।
  2. what() override करना भूल जाना, ताकि यह एक generic message return करे।
  3. const noexcept के बिना what() लिखना, जो base signature से match नहीं करता।
🔒

Chapter Quiz — Complete all 5 topics to unlock

0/5 topics done

Complete these topics first:

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.