我想创建一个银行应用程序,它可以处理错误并抛出异常来处理发生的错误。这些是我希望程序处理的异常:
这是我的代码:
使用静态System.Console; 命名空间Bank { 公共部门班级:表格 { 公共银行() { 的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;
}
}
}
我真的需要帮助来处理使用异常的错误。
答案 0 :(得分: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);
}
}
附加说明: