Custom Exception Creator - Problem

Create custom exception classes for a banking application that can handle different types of errors that occur during banking operations.

Requirements:

  • Create InsufficientFundsError exception for when account balance is too low
  • Create InvalidAmountError exception for negative or zero transaction amounts
  • Create AccountLockedError exception for when account is locked/frozen

Each exception should:

  • Accept a custom error message in the constructor
  • Have a default message if none is provided
  • Be properly structured as exception classes

Implement a BankAccount class that uses these exceptions and a function that demonstrates their usage by attempting various operations and catching the exceptions.

Input & Output

Example 1 — Successful Withdrawal
$ Input: account_balance = 100, transaction_amount = 50
Output: Success: Balance is now 50
💡 Note: Account has sufficient funds ($100), withdrawal of $50 succeeds, leaving balance of $50
Example 2 — Insufficient Funds
$ Input: account_balance = 100, transaction_amount = 150
Output: InsufficientFundsError: Insufficient funds in account
💡 Note: Account balance ($100) is less than withdrawal amount ($150), triggers InsufficientFundsError
Example 3 — Invalid Amount
$ Input: account_balance = 100, transaction_amount = -50
Output: InvalidAmountError: Invalid transaction amount
💡 Note: Negative transaction amount (-$50) is invalid, triggers InvalidAmountError

Constraints

  • 1 ≤ account_balance ≤ 106
  • -1000 ≤ transaction_amount ≤ 106
  • Exception classes must inherit from base Exception class
  • Each exception must have default and custom message constructors

Visualization

Tap to expand
BANKING OPERATIONSAccount Balance$100Withdraw $150 (Insufficient)Withdraw -$50 (Invalid)Account LockedWithdraw $50 (Valid)EXCEPTION HANDLING1Create Custom Exceptions2Implement BankAccount Class3Check Transaction Conditions4Throw Appropriate ExceptionException Types:InsufficientFundsErrorInvalidAmountErrorAccountLockedErrorERROR RESPONSEInsufficientFundsError:Insufficient funds in accountInvalidAmountError:Invalid transaction amountAccountLockedError:Account is lockedSuccess:Balance is now $50Key Insight:Custom exceptions provide specific, actionable error information instead of generic failures,enabling better user experience and precise error handling in banking applications.TutorialsPoint - Custom Exception Creator | Enhanced Exception Classes with Context
Asked in
Microsoft 25 Amazon 30 Google 20 Apple 15
12.5K Views
Medium Frequency
~15 min Avg. Time
450 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen