🎨
Exception Handling

Custom Exception Classes

Apna Exception Type Banao
💡 Custom exceptions apne khud ke specific "alarm types" banane jaisa hai — generic "kuch galat hua" alarm ke bajaye, specific alarms jaise "fire alarm" ya "smoke alarm", jo exact problem batate hain.

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;
}
🎨
Custom exceptions apne khud ke specific "alarm types" banane jaisa hai — generic "kuch galat hua" alarm ke bajaye, specific alarms jaise "fire alarm" ya "smoke alarm", jo exact problem batate hain.
1 / 2
⚡ झट से Recap
  • std::exception se inherit karke custom exception types banao
  • what() override karke meaningful error message do
  • Application-specific errors ko clearly represent karta hai
इस page में (2 subtopics)

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;
}
💡Tip: catch (const AppException&) DatabaseException ko bhi pakad leta hai (polymorphism ki wajah se) — isliye exception hierarchies design karte waqt, catch order specific-se-generic rakhna zaroori hai.

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;
}
⚠️Common Mistake: noexcept function ke andar agar galti se exception throw ho jaaye (jaise ek called function exception throw kare), std::terminate() call hota hai — program turant crash, koi graceful handling nahi. noexcept sirf tab lagao jab genuinely guarantee ho sakta ho.