Custom Exception Classes
Built-in exceptions (runtime_error, logic_error) generic hain. Real-world applications mein usually custom exception classes banate hain (std::exception se inherit karke) — jo application-specific errors ko clearly represent karte hain, aur extra info bhi carry kar sakte hain (jaise error code, invalid value).
std::exception se inherit karke, what() method ko override karna padta hai — ye standard interface hai jo saare exceptions follow karte hain, isliye generic catch (const exception &e) bhi kaam karta hai custom types ke liye bhi.
#include <exception>
using namespace std;
class InvalidAgeException : public exception {
private:
string message;
public:
InvalidAgeException(int age) {
message = "Invalid age: " + to_string(age);
}
const char* what() const noexcept override {
return message.c_str();
}
};
void setAge(int age) {
if (age < 0 || age > 150) {
throw InvalidAgeException(age);
}
cout << "Age set to " << age << endl;
}
int main() {
try {
setAge(200);
} catch (const InvalidAgeException &e) {
cout << "Caught: " << e.what() << endl; // "Caught: Invalid age: 200"
}
return 0;
}- std::exception se inherit karke custom exception types banao
- what() override karke meaningful error message do
- Application-specific errors ko clearly represent karta hai
Custom exceptions ki apni hierarchy bhi ban sakti hai — ek base "AppException" class, aur usse derived specific exceptions (jaise "DatabaseException", "NetworkException"). Isse ek hi catch (const AppException&) se saare app-specific errors pakad sakte ho, ya specific type se sirf ek category.
class AppException : public exception {
protected:
string message;
public:
AppException(string msg) : message(msg) {}
const char* what() const noexcept override { return message.c_str(); }
};
class DatabaseException : public AppException {
public:
DatabaseException(string msg) : AppException("DB Error: " + msg) {}
};
int main() {
try {
throw DatabaseException("Connection failed");
} catch (const AppException &e) { // base class catch — Derived bhi pakad leta hai
cout << e.what() << endl; // "DB Error: Connection failed"
}
return 0;
}noexcept keyword ek function ko mark karta hai ki wo KABHI exception throw nahi karega — compiler isse optimize kar sakta hai, aur agar accidentally exception throw ho jaaye is function se, program turant terminate() ho jaata hai (crash, exception propagate nahi hoti).
void safeFunction() noexcept {
cout << "Guaranteed no exceptions" << endl;
}
double divide(double a, double b) noexcept {
if (b == 0) return 0; // exception throw karne ke bajaye, safe default return
return a / b;
}