Labs ICT
Pro Login

Custom Exceptions

Custom Exception Classes

For structured error handling, define your own exception class that extends std::exception. Override the what() method to return a descriptive error message.

Benefits

Custom exceptions carry domain-specific information and can be caught by type. They integrate seamlessly with existing try/catch patterns.

#include <iostream>
#include <exception>
using namespace std;

class InsufficientFunds : public exception {
public:
  const char* what() const noexcept override {
    return "Not enough funds for withdrawal";
  }
};

class BankAccount {
private:
  double balance;
public:
  BankAccount(double b) {
    balance = b;
  }

  void withdraw(double amount) {
    if (amount > balance)
      throw InsufficientFunds();
    balance -= amount;
  }

  double getBalance() {
    return balance;
  }
};

int main() {
  BankAccount acc(100);
  try {
    acc.withdraw(200);
  } catch (const InsufficientFunds& e) {
    cout << "Exception: " << e.what() << "\n";
  }
  return 0;
}
Try it Yourself →