Program for custom exception handling :
#include <iostream>
#include <string>
#include <exception>
using namespace std;
// Custom exception for insufficient balance
class InsufficientBalanceException : public exception {
public:
const char* what() const noexcept override {
return "Error: Insufficient balance for withdrawal!";
};
// Custom exception for negative deposit
class NegativeDepositException : public exception {
public:
const char* what() const noexcept override {
return "Error: Deposit amount cannot be negative!";
};
// Custom exception for invalid account number
class InvalidAccountException : public exception {
public:
const char* what() const noexcept override {
return "Error: Invalid account number!";
}
};
// BankAccount class
class BankAccount {
private:
string accNumber;
double balance;
public:
BankAccount(string accNo, double bal) {
if ([Link]() != 5) {
throw InvalidAccountException();
accNumber = accNo;
balance = bal;
void deposit(double amount) {
if (amount < 0)
throw NegativeDepositException();
balance += amount;
cout << "Deposited: ₹" << amount << endl;
cout << "Current Balance: ₹" << balance << endl;
void withdraw(double amount) {
if (amount > balance)
throw InsufficientBalanceException();
balance -= amount;
cout << "Withdrawn: ₹" << amount << endl;
cout << "Remaining Balance: ₹" << balance << endl;
};
int main() {
try {
string accNo;
double bal;
cout << "Enter 5-digit Account Number: ";
cin >> accNo;
cout << "Enter Initial Balance: ₹";
cin >> bal;
BankAccount acc(accNo, bal);
cout << "\n--- Transaction Menu ---\n";
cout << "1. Deposit Money\n2. Withdraw Money\n";
int choice;
cout << "Enter choice: ";
cin >> choice;
if (choice == 1) {
double amt;
cout << "Enter amount to deposit: ₹";
cin >> amt;
[Link](amt);
else if (choice == 2) {
double amt;
cout << "Enter amount to withdraw: ₹";
cin >> amt;
[Link](amt);
else {
throw runtime_error("Invalid menu choice!");
catch (const InvalidAccountException &e) {
cout << [Link]() << endl;
catch (const NegativeDepositException &e) {
cout << [Link]() << endl;
catch (const InsufficientBalanceException &e) {
cout << [Link]() << endl;
catch (const exception &e) { // Catch-all for other standard exceptions
cout << "Standard Exception: " << [Link]() << endl;
cout << "\nProgram executed successfully (with proper exception handling)." << endl;
return 0;
}
Sample Output 1:
Enter 5-digit Account Number: 12345
Enter Initial Balance: ₹5000
--- Transaction Menu ---
1. Deposit Money
2. Withdraw Money
Enter choice: 1
Enter amount to deposit: ₹-1000
Error: Deposit amount cannot be negative!
Program executed successfully (with proper exception handling).
Sample output 2:
Enter 5-digit Account Number: 12345
Enter Initial Balance: ₹5000
--- Transaction Menu ---
1. Deposit Money
2. Withdraw Money
Enter choice: 1
Enter amount to deposit: ₹-1000
Error: Deposit amount cannot be negative!
Program executed successfully (with proper exception handling).