【问题标题】:Bank Application that Handles Exceptions处理异常的银行应用程序
【发布时间】:2017-09-19 22:04:54
【问题描述】:

我想创建一个银行应用程序,它可以处理错误并抛出异常来处理发生的错误。这些是我希望程序处理的异常:

  1. 从帐户中提取的金额超过当前余额。这应该会打印一条错误消息。
  2. 尝试在尚未创建的帐户上进行交易(存款、取款或余额)。
  3. 尝试创建超过最大数量 (19) 的帐户。

这是我的代码:

使用静态 System.Console; 命名空间银行 { 公共部分类银行:表格 { 公共银行() { 初始化组件(); }

    private int _nextIndex = 0;

    Accounts[] arrayAccounts = new Accounts[19];


    private void createAccountButton_Click(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(accountIDTexTBox.Text)) return;
        var account = new Accounts();
        int accountID;
        int balance = 0;

        bool success = int.TryParse(accountIDTexTBox.Text, out accountID);


        if (!int.TryParse(amountTextBox.Text, out balance))
        {
            result.Text = "Invalid Format in the Amount Fields please correct";
            //   MessageBox.Show("Invalid Format in the Amount Fields please correct");
        }


        if (balance < 300)
        {
            label5.Text = ("initial deposit must be $300 or greater");
        }

        else if (success)
        {
            account.AccountId = accountID;
            account.Balance = balance;
            arrayAccounts[_nextIndex] = account;
            OutPutLabel.Text = "Account # " + accountID + " open with balance of " + balance;
        }


        else
        {
            result.Text = ("invalid AccountID entered, Please Correct");
        }
    }

    private Accounts GetAccounts(int id)
    {

            return arrayAccounts.Where(x => x.AccountId == id).FirstOrDefault();
    }


    private void DepositRadioButton_CheckedChanged(object sender, EventArgs e)
    {
       // if (string.IsNullOrEmpty(accountIDTexTBox.Text)) return;
        int amount = 0;
        int accountID;
        bool succcess1 = int.TryParse(accountIDTexTBox.Text, out accountID);
        bool success2 = int.TryParse(amountTextBox.Text, out amount);
        try
        {
            if (succcess1 && success2 && amount > 0)
            {
                var selectedAccount = GetAccounts(accountID);
                selectedAccount.Balance += amount;
                OutPutLabel.Text = "Account # " + accountID + " deposit " + amount;
            }
            else if (!succcess1)
            {
                result.Text = "You are attempting to deposit  to a non-number ID";
            }
            else if (!success2)
            {
                result.Text = "Youu are Attempting to deposit \n "+ 
                    "to a non_Number amount  \n Please reenter the amount";
            }
        }
        catch(NullReferenceException)
        {
            result.Text = "Account has not being Created , \n Please create an Account";
        }

    }

    private void WithdrawRadioButton_CheckedChanged(object sender, EventArgs e)
    {
       // if (string.IsNullOrEmpty(accountIDTexTBox.Text)) return;
        int amount = 0;
        int accountID;
        bool success1 = int.TryParse(accountIDTexTBox.Text, out accountID);

        bool success2 = int.TryParse(amountTextBox.Text, out amount);
        try
        {
            if (success1 && success2 && amount > 0)
            {
                var selectedAccount = GetAccounts(accountID);
                selectedAccount.Balance -= amount;
                OutPutLabel.Text = amount + " withdraw from account # " + accountID;
            }


            else if (!success1)
        {
            result.Text = "You are attempting to withdraw from a non-number ID";
        }
        else if (!success2)
        {
            result.Text = "Youu are Attempting to Withdraw \n " +
                "a non_Number amount  \n Please reenter the amount";
        }

    }
        catch (NullReferenceException)
        {
            result.Text = "Account has not being created , \n Please Create Account";

        }

    }

    private void exceuteButton_Click(object sender, EventArgs e)
    {
       /// if (string.IsNullOrEmpty(accountIDTexTBox.Text)) return;
    }

    private void balanceRadioButton_CheckedChanged(object sender, EventArgs e)
    {
        int amount = 0;
        int accountID;
        bool success1 = int.TryParse(accountIDTexTBox.Text, out accountID);
        try
        {
            if (success1)
            {
                var selectedAccount = GetAccounts(accountID);
                OutPutLabel.Text = "Account # " + accountID + " has a balance of " + selectedAccount.Balance;
            }
        }
        catch (NullReferenceException)
        {
            result.Text = "Account has not being Created"
                + "\n Please create account.";

        }
    }
}

class NegativeNumberException : Exception
{
    private static string msg = "The Amount you enter is a negative number";
    public NegativeNumberException() : base(msg)
    {
    }
}

我已经能够使用 TryParse 和 If/else 语句处理一些错误。有没有更好的方法来使用异常来处理这些错误。

这是帐户类的代码:

public class Accounts
{

    public int AccountId { get; set; }

    public decimal Balance { get; set; }

    public void Deposit(decimal amount)
    {
        Balance += amount;
    }

   public void Withdraw(decimal amount)
    {
        Balance -= amount;
    }
}

}

我真的需要帮助来使用异常处理这些错误。

【问题讨论】:

  • 对于初学者,您永远不需要捕获NullReferenceException。改为进行显式空检查。
  • 业务规则应该由您的代码检查和强制执行,而不是抛出异常。

标签: c# winforms exception


【解决方案1】:

首先,您必须在代码中创建请求的异常类型,我们稍后将使用它们。

public class InsufficientBalanceException : Exception
{
    // Exception for when a user tries to perform a withdrawal/deposit on an account with an insufficient balance of funds.
    public InsufficientBalanceException() { }

    public InsufficientBalanceException(string message)
    : base(message) { }

    public InsufficientBalanceException(string message, Exception inner)
    : base(message, inner) { }
}

public class InvalidAccountException : Exception
{
    // Exception for when a user is trying to perform an operation on an invalid account.
    public InvalidAccountException() { }

    public InvalidAccountException(string message)
    : base(message) { }

    public InvalidAccountException(string message, Exception inner)
    : base(message, inner) { }
}

public class InvalidNumberOfAccountsException : Exception
{
    // Exception for when a user is trying to create an account beyond the given limit.
    public InvalidNumberOfAccountsException() { }

    public InvalidNumberOfAccountsException(string message)
    : base(message) { }

    public InvalidNumberOfAccountsException(string message, Exception inner)
    : base(message, inner) { }
}

然后,您需要指定在什么条件下将抛出这些异常中的每一个。

请记住,您不想在实体类中执行此操作,因为它们旨在尽可能简单。

您很可能希望将该逻辑放入某种辅助类中(而不是在您在代码中显示的 UI 中)。无论如何,您的代码应该类似于以下内容:

public class AccountHelper
{
    public Account GetAccount(int accountID)
    {
        /* Put some logic in here that retrieves an account object based on the accountID.
         * Return Account object if possible, otherwise return Null */
        return new Account();
    }
    public bool IsValidAccount(int accountID)
    {
        /* Put some logic in here that validates the account.
         * Return True if account exists, otherwise return False */
        return true;
    }
    public bool IsValidAmount(decimal amount)
    {
        /* Put some logic in here that validates the amount.
         * Return True if amount is valid, otherwise return False */
        return amount > 0;
    }
    public bool IsSufficientAmount(Account account, decimal amount)
    {
        /* Put some logic in here that validates the requested amount against the given account.
         * Return True if account balance is valid, otherwise return False */
        if (account == null)
            return false;

        return account.Balance >= amount;
    }
    public void DepositToAccount(int accountID, decimal amount)
    {
        Account account = null;

        if (!IsValidAmount(amount))
            throw new InvalidAmountException();

        if (!IsValidAccount(accountID))
            throw new InvalidAccountException();

        account = GetAccount(accountID);

        account.Deposit(amount);
    }
    public void WithdrawFromAccount(int accountID, decimal amount)
    {
        Account account = null;

        if (!IsValidAmount(amount))
            throw new InvalidAmountException();

        if (!IsValidAccount(accountID))
            throw new InvalidAccountException();

        account = GetAccount(accountID);

        if (!IsSufficientAmount(account, amount))
            throw new InsufficientBalanceException();

        account.Withdraw(amount);
    }
}

附加说明:

  1. 您的 Accounts 类应重命名为 Account,因为每个 该对象的实例代表一个帐户。
  2. 您应该尝试将业务逻辑与 UI 分开。它 将事情混在一起不是一个好习惯,因为稍后你 如果必须进行更改,可能会遇到问题。这将是 如果您保留所有代码,则更容易找到所需的代码行 您的逻辑在一个文件中并在 UI 之外。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-01
    • 2014-05-04
    • 1970-01-01
    • 2012-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多