C# 处理异常的银行应用程序

C# 处理异常的银行应用程序,c#,winforms,exception,C#,Winforms,Exception,我想创建一个银行应用程序,它可以处理错误并抛出异常来处理发生的错误。以下是我希望程序处理的例外情况: 从账户中提取超过当前余额的款项。这将打印一条错误消息 试图在尚未创建的帐户上进行交易(存款、取款或余额) 正在尝试创建超过最大帐户数(19)的帐户 这是我的密码: 使用静态系统控制台; 名称空间库 { 公共部分类银行:表格 { 公共银行() { 初始化组件(); } private int _nextIndex = 0; Accounts[] arrayAccounts = n

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

  • 从账户中提取超过当前余额的款项。这将打印一条错误消息
  • 试图在尚未创建的帐户上进行交易(存款、取款或余额)
  • 正在尝试创建超过最大帐户数(19)的帐户
  • 这是我的密码:

    使用静态系统控制台; 名称空间库 { 公共部分类银行:表格 { 公共银行() { 初始化组件(); }

        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)
        {
        }
    }
    
    }


    在使用异常处理这些错误方面,我确实需要帮助。

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

    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);
        }
    }
    
    附加说明:

  • 您的Accounts类应重命名为Account,如下所示: 该对象的实例表示一个帐户
  • 您应该尝试将业务逻辑与UI分离 以后再把事情混在一起不是一个好习惯 如果必须进行更改,可能会遇到问题。它将 如果您保留了所有 您的逻辑在一个文件中,在UI之外

  • 对于初学者,您永远不需要捕获
    NullReferenceException
    。而是执行显式空检查。业务规则应该由您的代码检查和强制执行,而不是引发异常。
    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);
        }
    }