c#


Bank Application that Handles Exceptions


I want to create a Banking Application that can handle errors and throw exceptions to handle does errors that occur. These are the Exceptions i want the program to handle :
Withdrawing more than the current balance from an account. This should print an error message.
Attempting a transaction (deposit, withdrawal, or balance) on an account that has not been created yet.
Trying to create more than the maximum number (19) of accounts.
Here is My Code :
using static System.Console;
namespace Bank
{
public partial class Bank : Form
{
public 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)
{
}
}
I have being able to handle some of the errors using TryParse and If/else statements. Is there a better way to handle those errors using Exceptions.
here is the code for Account Class:
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;
}
}
}
I really need help on handle those errors using exceptions.
First you'll have to create the requested exception types in your code which we will be using later on.
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) { }
}
Then, you need to specify in what conditions you'll be throwing each one of those exceptions.
Keep in mind you do not want to do this in your entity class since those are designed to be kept as simple as possible.
You'll most likely want to put that logic into some sort of a helper class (and not in the UI as you display in your code). Regardless, your code should look similar to the following:
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);
}
}
Additional Notes:
Your Accounts class should be renamed to Account, as each
instance of that object represents one single account.
You should be trying to separate your business logic from the UI. It
is not a good practice to mix things up together as later on you
might face problems in case changes will have to be made. It will be
much easier to locate the required lines of code if you keep all of
your logic in one file and outside the UI.

Related Links

dbContext.SaveChanges() not saving and not outputting an error
Failed to assign to property 'Windows.UI.Xaml.FrameworkElement.Height'
Delete directory of files, UI is not updating
MongoDB very slow read performance on server
With LogOff record in database and deleting cookie behind the Session_End ( ) in Global.asax
Other text input methods?
Can we convert an EXE into a program which can be Auto-Installed without any Clicks or Commands just after download, or may be on System Restart [closed]
How can I generate LINQ queries automatically from IQueryable<T> and LINQ POCO classes?
Ajax / LinqtoSql / multiple insert conflict primary key
tinyint in SQL Server to byte in C#
How can I bind a datatemplate to a observablecollection so that they all show up?
C# click on control
Sharing memory between managed and unmanaged code with P/Invoke
How to download and store an image using Windows.Web.Http?
Namespace path in WPF XAML
Angle Normalization C#

Categories

HOME
ckan
system-calls
sip
ldap
display
gaussian
where
app-store
coordinates
symfony-sonata
rmarkdown
samsung-gear-s2
unreal-engine4
osclass
virtualenv
bookmarklet
taxonomy
aiml
include-path
coccinelle
multipart
matlab-gui
oracle-golden-gate
waterfall
deployment-descriptor
pydub
tftp
angular2-changedetection
dynamics-ax-2012-r3
osgi-bundle
choco
unity3d-5
ilog
apache-falcon
sampling
aweber
device-driver
stochastic-process
framebuffer
jibx
latency
linkurious
libzip
npoco
automapper-4
xmldom
google-cloud-shell
ear
jcifs
seyren
grib
iban
msiexec
visual-web-developer
rowname
mate-desktop
vga
angularfire
phpdesigner
mod
radar-chart
nugetgallery
jsondoc
instabug
kramdown
magnet-uri
exchange-server-2007
traminer
openhab
veeam
mri
fedena
clearcanvas
nsurlrequest
visual-c#-express-2010
debuggervisualizer
rssi
nodeunit
zend-db-table
xrandr
usersettings
dynamic-expresso
exi
nsautoreleasepool
generator-expression
antixsslibrary
feincms
quit
xpolog
peoplepicker
azure-appfabric
virtual-destructor
database-agnostic
newspeak
djangoappengine
expander

Resources

Encrypt Message