0% found this document useful (0 votes)
61 views5 pages

Java Bank Account Withdrawal Code

The document describes a Java program for a simple banking application that includes custom exceptions for insufficient funds and invalid account numbers. It features a BankAccount class for managing account details and a BankApp class for user interaction, including withdrawal operations with error handling. The program demonstrates handling various scenarios such as valid transactions, invalid account numbers, and insufficient funds through try-catch blocks.

Uploaded by

santhoshupsc5
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
61 views5 pages

Java Bank Account Withdrawal Code

The document describes a Java program for a simple banking application that includes custom exceptions for insufficient funds and invalid account numbers. It features a BankAccount class for managing account details and a BankApp class for user interaction, including withdrawal operations with error handling. The program demonstrates handling various scenarios such as valid transactions, invalid account numbers, and insufficient funds through try-catch blocks.

Uploaded by

santhoshupsc5
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

import [Link].

Scanner;

// Custom exception for insufficient funds

class InsufficientFundsException extends Exception {

public InsufficientFundsException(String message) {

super(message);

// Custom exception for invalid account number

class InvalidAccountNumberException extends Exception {

public InvalidAccountNumberException(String message) {

super(message);

public class BankAccount {

private String accountNumber;

private double balance;

// Constructor to initialize account with account number and balance

public BankAccount(String accountNumber, double balance) {

[Link] = accountNumber;

[Link] = balance;

// Method to withdraw money from the account

public void withdraw(double amount) throws InsufficientFundsException {

if (amount > balance) {

throw new InsufficientFundsException("Insufficient funds! Your balance is " + balance);


}

balance -= amount;

[Link]("Withdrawal successful! New balance: " + balance);

// Method to get the account balance

public double getBalance() {

return balance;

// Method to get account number

public String getAccountNumber() {

return accountNumber;

class BankApp {

public static void main(String[] args) {

Scanner scanner = new Scanner([Link]);

// Predefined bank accounts

BankAccount account1 = new BankAccount("ACC123", 1000.00);

BankAccount account2 = new BankAccount("ACC456", 500.00);

try {

[Link]("Welcome to the bank!");

// Get account number input

[Link]("Enter your account number: ");

String enteredAccountNumber = [Link]();


// Validate account number

BankAccount account = null;

if ([Link]([Link]())) {

account = account1;

} else if ([Link]([Link]())) {

account = account2;

if (account == null) {

throw new InvalidAccountNumberException("Invalid account number! Please check and try


again.");

// Get withdrawal amount input

[Link]("Enter amount to withdraw: ");

double withdrawalAmount = [Link]();

// Attempt withdrawal

[Link](withdrawalAmount);

} catch (InvalidAccountNumberException e) {

[Link]("Error: " + [Link]());

} catch (InsufficientFundsException e) {

[Link]("Error: " + [Link]());

} catch (Exception e) {

[Link]("An unexpected error occurred: " + [Link]());

} finally {

[Link]();

[Link]("Thank you for using our banking system.");

} }}
Explanation:

1. Custom Exceptions:

o InsufficientFundsException: This exception is thrown if the withdrawal amount is


greater than the account balance. It takes a message as input and passes it to the
parent Exception class.

o InvalidAccountNumberException: This exception is thrown if the user enters an


invalid account number. It also takes a message to be displayed.

2. BankAccount Class:

o This class represents a bank account with methods to withdraw money (withdraw())
and to get account details like balance and account number.

o The withdraw() method throws an InsufficientFundsException if the balance is lower


than the withdrawal amount.

3. BankApp Class:

o This is the main application that simulates a user interacting with the bank.

o First, the program asks the user for an account number and checks if it's valid.

o If the account number is invalid, the program throws an


InvalidAccountNumberException.

o Then, it asks the user for the withdrawal amount. If the amount is greater than the
balance, it throws an InsufficientFundsException.

o The program uses a try-catch block to handle exceptions and provide feedback to the
user.

o The finally block ensures that the Scanner resource is closed, preventing resource
leaks.

Example Execution:

Scenario 1: Valid Account and Sufficient Funds

Welcome to the bank!

Enter your account number: ACC123

Enter amount to withdraw: 200

Withdrawal successful! New balance: 800.0

Thank you for using our banking system.

Scenario 2: Invalid Account Number

Welcome to the bank!


Enter your account number: ACC999

Error: Invalid account number! Please check and try again.

Thank you for using our banking system.

Scenario 3: Insufficient Funds

Welcome to the bank!

Enter your account number: ACC123

Enter amount to withdraw: 1500

Error: Insufficient funds! Your balance is 1000.0

Thank you for using our banking system.

Common questions

Powered by AI

Having hardcoded account numbers in the BankApp class limits scalability, as any addition or modification of accounts would require altering the source code directly, reducing flexibility and increasing maintenance efforts. A potential solution involves integrating a database or an external data source to manage account information dynamically. This approach allows for easier management and expansion, where account information can be read and modified without altering the application code, fostering a scalable and more maintainable application architecture .

The BankApp showcases best practices in Java exception handling and user feedback by demonstrating the importance of using custom exceptions for specific error scenarios and handling them with informative messages. By distinguishing InvalidAccountNumberException and InsufficientFundsException, the application provides targeted feedback that is relevant to the user's actions, enhancing the user experience through clarity and guidance. Moreover, the use of a try-catch-finally pattern exemplifies a structured approach to error management that ensures code robustness and resource efficiency .

Custom exceptions in the BankAccount class, such as InsufficientFundsException and InvalidAccountNumberException, serve to encapsulate specific error conditions relating to account operations. These custom exceptions allow for clear and meaningful error messages that are directly relevant to the issues faced by the user. By throwing these exceptions when specific constraints are violated (e.g., insufficient funds for a withdrawal), the program can quickly identify and handle errors in a structured manner, improving maintainability and readability .

The concept of exception handling improves the robustness of the BankApp program by preventing the application from crashing due to errors like invalid inputs or operations that violate business logic. Specifically, the program explicitly manages two custom exceptions: InvalidAccountNumberException, which is thrown when the user enters an incorrect account number, and InsufficientFundsException, which is triggered when a withdrawal amount exceeds the balance. These exceptions are caught and handled in a try-catch block, allowing the program to provide informative feedback to the user and continue running. The use of a finally block ensures resources are properly closed, preventing resource leaks .

The withdraw method enforces business rules by checking if the withdrawal amount is greater than the current balance. If this rule is violated, the method throws an InsufficientFundsException, preventing the transaction from being completed. The consequence of not adhering to these rules would be allowing overdrafts, potentially leading to negative balances and financial inaccuracies. By enforcing these rules with exceptions, the method ensures that the account's balance integrity is maintained .

Omitting the finally block in the BankApp class could lead to resource leaks, particularly with the Scanner object used for input. If an exception occurs and the finally block is not included, the Scanner might remain open, consuming system resources unnecessarily, and potentially leading to memory leaks or file descriptor exhaustion over time. Including the finally block ensures that the Scanner is closed after its use, regardless of whether an exception is thrown, thereby enhancing the program's reliability and resource integrity .

The try-catch-finally construct is vital for comprehensive error handling and resource management in Java, as demonstrated in the BankApp. Within this structure, the try block defines the main code execution, where exceptions may occur. Identified exceptions are caught in the catch blocks, allowing custom messages to guide users in resolving issues like invalid accounts and insufficient funds. The finally block, executing regardless of whether an exception is thrown, ensures the closure and cleanup of used resources (such as the Scanner), thereby preventing resource leaks and maintaining application stability .

Using the Scanner class for input handling in BankApp is efficient for simple command-line applications; it allows straightforward reading of user input. However, improvements could be made by validating inputs to prevent wrong data types or unexpected inputs, which might bypass input expectations unintentionally. Moreover, consider implementing input sanitation techniques to improve security and reliability. For larger applications, switching to a graphical user interface (GUI) would enhance user experience and allow more robust input handling .

The program uses try-catch blocks to detect and mitigate potential runtime exceptions. Specific exceptions, such as InvalidAccountNumberException and InsufficientFundsException, are caught to provide targeted feedback to users, thus preventing the program from crashing and maintaining user interaction flow. Additionally, a generic catch block covers any other unexpected exceptions. This structure is effective in ensuring the program handles known error conditions gracefully and provides a fallback for any other unforeseen errors, contributing to its robustness .

The BankApp program ensures user-friendly interaction by providing clear prompts and error messages during account number validation and transaction processing. When an incorrect account number is entered, the InvalidAccountNumberException provides a specific message prompting the user to check their input. Similarly, if a withdrawal exceeds the balance, the InsufficientFundsException informs the user of the insufficient funds along with the current balance. This feedback helps guide the user toward corrective actions, thereby enhancing the user experience while safeguarding operations with rigorous error validation mechanisms .

You might also like