2017-04-23 34 views
0

我想創建一個銀行應用程序,該應用程序可以處理錯誤並拋出異常來處理髮生的錯誤。這些是我希望程序處理的例外情況:處理異常的銀行應用程序

  1. 從賬戶中提取超過當前餘額。這應該打印一條錯誤消息。
  2. 嘗試對尚未創建的帳戶進行交易(存款,提款或餘額)。
  3. 嘗試創建超過最大數量(19)的帳戶。

這裏是我的代碼:

使用靜態System.Console; 命名空間銀行 { 公共部分類銀行:形式 { 公共銀行() { 的InitializeComponent(); }

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; 
    } 
} 

}

我真的需要處理使用異常的那些錯誤的幫助。

+2

對於初學者來說,你永遠不應該需要捕獲一個'NullReferenceException'。改爲進行顯式空檢查。 –

+2

業務規則應該由代碼檢查和強制,而不是拋出異常。 – nabuchodonossor

回答

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. 賬戶類應該被重新命名爲帳戶,作爲對象的每個 實例代表一個單一的帳戶。
  2. 您應該嘗試將您的業務邏輯與用戶界面分開。它 是不是一個好的做法混合在一起,因爲你後來可能會遇到問題,如果必須進行更改。如果您將所有的 邏輯保存在一個文件中並且在UI之外,那麼定位所需的代碼行將會更容易得到 。