Custom Exception Handling

This example shows how to create and handle custom exceptions.

class InsufficientFundsException implements Exception {
  final String message;

  InsufficientFundsException(this.message);

  @override
  String toString() => 'InsufficientFundsException: $message';
}

class BankAccount {
  double balance;

  BankAccount(this.balance);

  void withdraw(double amount) {
    if (amount > balance) {
      throw InsufficientFundsException('Cannot withdraw \$${amount.toStringAsFixed(2)} with balance of \$${balance.toStringAsFixed(2)}');
    }
    balance -= amount;
    print('Withdrawn: \$${amount.toStringAsFixed(2)}. New balance: \$${balance.toStringAsFixed(2)}');
  }
}

void main() {
  var account = BankAccount(100);

  try {
    account.withdraw(50);
    account.withdraw(60);
  } catch (e) {
    print(e);
  }
}

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *