Answered by:
Exception

Question
-
Hi,this is my code and i need help to perform the following operation..Can anyone pls help me
Step 1
using System;
In GetAccount method, modify its code so that if account is not found in the allAccounts list throw an exception with appropriate error message. The exception thrown from here will bubble up to the caller and has to handled by the caller.
Step 2
Wherever GetAccount method is in use (e.g. Show an Account choice) enclose relevant statements in try block which you suspect, may be affected by exception thrown by GetAccount. Write supporting catch to show user friendly message displaying account is not found.
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
namespace CATS
{
public struct Customer
{
public string CustomerName;
public string CustomerAddress;
}
public enum AccountType
{
Current,
Savings
}
public delegate void BalanceChangeHandler(string message, decimal balanceNow);
public class BankAccount
{
private int _accountNumber;
public Customer Customer;
public decimal _balance;
public static int nextNumber = 1001;
public AccountType TypeAccount;
private static decimal QuickWithdrawAmount = 100;
public event BalanceChangeHandler BalanceChanged;
private Queue<BankTransaction> Transaction;
public int AccountNumber
{
get
{
return _accountNumber;
}
}
public decimal Balance
{
get
{
return _balance;
}
set
{
if (value >= 0)
{
_balance = value;
}
else
{
Console.WriteLine("Balance cannot be nagative");
}
}
}
private BankAccount()
{
this.Transaction = new Queue<BankTransaction>();
this._accountNumber = BankAccount.GetNextAccountNumber();
Console.WriteLine("Your new account number:{0} ", this.AccountNumber);
Console.WriteLine("\r");
Console.WriteLine("Enter customer Name: ");
this.Customer.CustomerName = Console.ReadLine();
Console.WriteLine("\nEnter customer Address:");
this.Customer.CustomerAddress = Console.ReadLine();
Console.WriteLine("\nEnter Opening Balance:");
this.Balance = decimal.Parse(Console.ReadLine());
Console.WriteLine("press 'c' or 'C' for current and 's' or 'S' for savings");
if ("cC".Contains(Console.ReadLine().Trim()))
{
this.TypeAccount = AccountType.Current;
}
else
{
this.TypeAccount = AccountType.Savings;
}
GC.SuppressFinalize(this);
}
public static BankAccount CreateNewAccount()
{
return new BankAccount();
}
public decimal Deposit(decimal amount)
{
if (amount > 0)
{
this.Balance += amount;
if (BalanceChanged != null)
{
string message = string.Format("\nDeposited:{0},New Balance:{1} on{2}", amount, this.Balance, DateTime.Now);
BalanceChanged(message, this.Balance);
this.Transaction.Enqueue(new BankTransaction("Deposited", amount, DateTime.Now));
}
}
return this.Balance;
}
public bool WithDraw(decimal amount)
{
bool sufficientfunds = this.Balance >= amount;
if (sufficientfunds)
{
this.Balance -= amount;
if (BalanceChanged != null)
{
string message = string.Format("\nWithdrawn:{0} ,New Balance: {1} on {2}", amount, this.Balance, DateTime.Now);
BalanceChanged(message, this.Balance);
this.Transaction.Enqueue(new BankTransaction("Withdrawn", amount, DateTime.Now));
}
}
return sufficientfunds;
}
public void ShowAccount()
{
Console.WriteLine("Account Number: {0}", this.AccountNumber);
Console.WriteLine("customer name: {0}", this.Customer.CustomerName);
Console.WriteLine("customer add: {0}", this.Customer.CustomerAddress);
Console.WriteLine("customer balance: {0}", this.Balance);
Console.WriteLine("customer type: {0}", this.TypeAccount);
this.GetAccounttrans();
Console.ReadLine();
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("\n AccountDetails");
sb.Append("\n ===================");
sb.Append(string.Format("\nAccount Number: {0}\n ", this.AccountNumber));
sb.Append(string.Format("CustomerName Number: {0}\n ", this.Customer.CustomerName));
sb.Append(string.Format("Account Number: {0}\n ", this.TypeAccount.ToString()));
sb.Append(string.Format("Account Number: {0} \n", this.Balance));
return sb.ToString();
}
private static int GetNextAccountNumber()
{
return nextNumber++;
}
public void Dispose()
{
Console.WriteLine("\nDear customer {0} we are now closing this account" + "\nplease collect your cheque of {1} from the bank ", this.Customer.CustomerName, this.Balance);
Console.ReadLine();
}
private void GetAccounttrans()
{
foreach (var bankTransaction in this.Transaction)
{
Console.WriteLine(bankTransaction);
}
}
class BankTransaction
{
string tranDesc;
decimal tranAmount;
DateTime tranWhen;
public string Description
{
get
{
return tranDesc;
}
}
public decimal Amount
{
get
{
return tranAmount;
}
}
public DateTime When
{
get
{
return tranWhen;
}
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("\n TransactionDetails");
sb.Append("\n ==================");
sb.Append(string.Format("\nTransaction Description: {0}", tranDesc));
sb.Append(string.Format("\nTransaction Amount : {0}", tranAmount));
sb.Append(string.Format("\nTransaction When: {0}", tranWhen));
return sb.ToString();
}
public BankTransaction(string Desc, decimal amt, DateTime dt)
{
tranDesc = Desc;
tranAmount = Amount;
tranWhen = dt;
}
}
}
class Program
{
static ArrayList allAccounts = new ArrayList();
static void Main(string[] args)
{
if (Login())
{
StartBanking();
Console.WriteLine("Thank You!!!");
Console.ReadLine();
}
else
{
Console.WriteLine("\n Invalid Please Try Again");
Console.ReadLine();
return;
}
}
static void StartBanking()
{
int screenChoice = -1;
do
{
Console.WriteLine("\r");
Console.WriteLine("1.Teller screen");
Console.WriteLine("\r");
Console.WriteLine("2.Customer screen");
Console.WriteLine("\r");
Console.WriteLine("0.Quit");
Console.WriteLine("\r");
//Console.WriteLine("Enter Your choice or press any key to exit");
bool success = int.TryParse(Console.ReadLine(), out screenChoice);
if (success)
{
switch (screenChoice)
{
case 1:
TellerScreen();
break;
case 2:
CustomerScreen();
break;
default:
Console.WriteLine("\n\nTHANK U FOR USING CATS:\n\n");
System.Environment.Exit(0);
break;
}
}
else
{
screenChoice = -1;
Console.WriteLine("\nInvalid Please Try Again");
}
Console.ReadLine();
}
while (screenChoice != 0);
}
static void account_BalanceChanged(string message, decimal balanceNow)
{
Console.WriteLine("sms:" + message);
}
static bool Login()
{
bool valid = false;
string username = string.Empty;
string password = string.Empty;
Console.WriteLine("\t WELCOME TO CATS\t");
Console.WriteLine("\n Please Enter Your Username and Password\n");
Console.WriteLine(" Username: \n");
username = Console.ReadLine().Trim();
Console.WriteLine("\n Password :\n");
Console.WriteLine("\r");
password = Console.ReadLine().Trim();
if (username.ToUpper() == "ADMIN" && password.Equals("Pa$$w0rd"))
valid = true;
else
valid = false;
return valid;
}
public static void CustomerScreen()
{
int customerchoice = -1;
BankAccount customerAccount = null;
customerAccount = GetAccount();
if (customerAccount == null)
{
Console.WriteLine("\nAccount Does not Exists");
return;
}
do
{
Console.WriteLine("\r");
Console.WriteLine("\n1.Show my balance\n");
Console.WriteLine("\n2.Withdraw\n");
Console.WriteLine("\n3.Quick withdraw\n");
Console.WriteLine("\n4.Deposit\n");
Console.WriteLine("\n5.Show account details\n");
Console.WriteLine("\n0.Quit\n");
Console.WriteLine("\nEnter Your Choice or Press Any Key To Exit");
bool success = int.TryParse(Console.ReadLine(), out customerchoice);
if (success)
{
switch (customerchoice)
{
case 1:
customerAccount.ShowAccount();
break;
case 2:
Console.Write("\nEnter amount to withdraw: ");
decimal amt1 = decimal.Parse(Console.ReadLine());
customerAccount.WithDraw(amt1);
break;
case 3:
Console.Write("\nYou Requested Quick withdraw: ");
customerAccount.WithDraw(100);
break;
case 4:
Console.Write("\nEnter amount to deposit ");
decimal amt2 = decimal.Parse(Console.ReadLine());
customerAccount.Deposit(amt2);
break;
case 5:
customerAccount.ShowAccount();
break;
case 0:
return;
default:
Console.WriteLine("\nInvalid Please Try Again!!!!!!");
break;
}
}
else
{
customerchoice = -1;
Console.WriteLine("\nInvalid Please Try Again!!!!!!");
}
Console.ReadLine();
}
while (customerchoice != 0);
}
public static void TellerScreen()
{
int tellerchoice = -1;
do
{
Console.WriteLine("\r");
Console.WriteLine("\n1. Create new account: ");
Console.WriteLine("\n2. Display account details: ");
Console.WriteLine("\n3. Delete an account: ");
Console.WriteLine("\n4. Display all accounts: ");
// Console.WriteLine("5.show account details");
Console.WriteLine("\n0. Quit: ");
Console.WriteLine("\nEnter Your Choice or Press Any Key To Exit\n");
bool success = int.TryParse(Console.ReadLine(), out tellerchoice);
if (success)
{
switch (tellerchoice)
{
case 1:
BankAccount account = BankAccount.CreateNewAccount();
if (account != null)
{
Console.WriteLine("\nAccount successfully Created!!");
account.BalanceChanged += new BalanceChangeHandler(account_BalanceChanged);
allAccounts.Add(account);
}
break;
case 2:
BankAccount customerAccount = null;
customerAccount = GetAccount();
if (customerAccount == null)
{
Console.Write("\nAccount Does not exists");
}
else
{
customerAccount.ShowAccount();
}
break;
case 3:
BankAccount delCustomerAccount = null;
delCustomerAccount = GetAccount();
if (delCustomerAccount == null)
{
Console.Write("\nAccount Does not exists");
}
else
{
delCustomerAccount.Dispose();
allAccounts.Remove(delCustomerAccount);
}
break;
case 4:
Console.Write("\nAll Account Details...");
Console.Write("\n=======================");
foreach (BankAccount current in allAccounts)
{
BankAccount ba = (BankAccount)current;
Console.WriteLine(ba.ToString());
Console.ReadLine();
}
break;
case 0:
return;
default:
Console.WriteLine("\nInvalid Please Try Again!!!");
break;
}
}
else
{
tellerchoice = -1;
Console.WriteLine("\nInvalid Please Try Again!!!");
}
Console.ReadLine();
}
while (tellerchoice != 0);
}
static BankAccount GetAccount()
{
BankAccount customerAccount = null;
long accountNumber = 0;
Console.WriteLine("\nEnter Your Account Number: ");
if (long.TryParse(Console.ReadLine(), out accountNumber))
{
foreach (BankAccount acct in allAccounts)
{
BankAccount current = acct;
if (current.AccountNumber == accountNumber)
{
customerAccount = current;
break;
}
}
}
else
{
Console.WriteLine("\nInvalid Please Try Again!!! ");
}
return customerAccount;
}
}
}
Friday, February 8, 2013 8:32 AM
Answers
-
I didn't look at the entire code because it is big but from what I saw in your try-catch statement from cuted code, you are trying to print out the exception two times.
Just use the code that you need to execute inside the try statement without:
throw new AccountNotFoundException("Sorry There Is An Error!!! Your Account Number Does Not Exist");
Because you can write that message in the catch statement, like this:
catch (AccountNotFoundException e) { Console.WriteLine("That account does not exist!");//or similar message }
Microsoft Student Parnter Microsoft Technology Associate
- Proposed as answer by Tonchi91 Sunday, February 10, 2013 1:53 AM
- Unproposed as answer by Jason Dot Wang Monday, February 11, 2013 6:24 AM
- Marked as answer by Jason Dot Wang Monday, February 11, 2013 6:24 AM
Friday, February 8, 2013 6:49 PM
All replies
-
That sounds like you want help with your homework. I can give you pointers, but won't provide you with Code.
If you ever want to learn more about exception handling and throwing, this a good article. But you should not start there:
http://www.codeproject.com/Articles/9538/Exception-Handling-Best-Practices-in-NET
1. Exception and all Classes derived from it are Classes. In order to throw an exception you ahve to instantiate one. Example:
throw new Exception();
Thorwing an exception immediately jumps to the first try...catch block that can handle (catches the exact type or a type of a base class).If there is none in your code the .NET engine will catch it, display an error message and savefely close the application (removing all objects from memory).
Only exception is that "try...finally" statments on the way are executed.
Now throwign Exception as a very bad habit. You should always throw a more specific exception. You could even write one (with fitting parameters) yourself or take one from a ExistingClass (for example it is commong to throw "InvalidArgumentExceptions" when Functions get invalid parameters).
2. Write a try...catch block. Include every statement that requires a valid return value from GetAccount(), as if the do not get thier parameter they cannot work.
In the catch simply show a MessageBox (preferibly with Excpetion.toString());
Friday, February 8, 2013 9:03 AM -
I have proceeded in this way but it throws an error..need help please
THIS IS IN CLASS PROGRAM case 2: BankAccount customerAccount = null; customerAccount = GetAccount(); try { if (customerAccount == null) { throw new AccountNotFoundException("Sorry There Is An Error!!! Your Account Number Does Not Exist"); } } catch (AccountNotFoundException e) { Console.WriteLine(""+e); } BankAccount.ShowAccount(customerAccount); static BankAccount GetAccount() { BankAccount customerAccount = null; long accountNumber = 0; Console.WriteLine("\nEnter Your Account Number: "); if (long.TryParse(Console.ReadLine(), out accountNumber)) { foreach (BankAccount acct in allAccounts) { BankAccount current = acct; if (current.AccountNumber == accountNumber) { customerAccount = current; break; } } } else { throw new AccountNotFoundException("ACCount Does Not Exist"); //Console.WriteLine("\nInvalid Please Try Again!!! "); } return customerAccount; }
Friday, February 8, 2013 9:22 AM -
That a codeline like
throw new AccountNotFoundException("ACCount Does Not Exist");
Throws an exception IS THE POINT of writing the line. Exception's don't just materialise out of thin air. The developer of the code you use though it would be very usefull/nessesary to throw exceptions in certain scenarios.
Right now your code should only throw two Exceptions:
throw new AccountNotFoundException("ACCount Does Not Exist");
Is executed when parsing the UserInput Failed (TryParse returned False).
throw new AccountNotFoundException("Sorry There Is An Error!!! Your Account Number Does Not Exist");
Is thrown whenever GetAccount returns null, wich should only happen if the Number could be parsed but wasn't in the list. However as the allAccounts isn't filled with anything at all, no accoutn number can ever be found in it and the code will alwaysthrow an exception.- Proposed as answer by Jason Dot Wang Monday, February 11, 2013 6:24 AM
Friday, February 8, 2013 5:58 PM -
I didn't look at the entire code because it is big but from what I saw in your try-catch statement from cuted code, you are trying to print out the exception two times.
Just use the code that you need to execute inside the try statement without:
throw new AccountNotFoundException("Sorry There Is An Error!!! Your Account Number Does Not Exist");
Because you can write that message in the catch statement, like this:
catch (AccountNotFoundException e) { Console.WriteLine("That account does not exist!");//or similar message }
Microsoft Student Parnter Microsoft Technology Associate
- Proposed as answer by Tonchi91 Sunday, February 10, 2013 1:53 AM
- Unproposed as answer by Jason Dot Wang Monday, February 11, 2013 6:24 AM
- Marked as answer by Jason Dot Wang Monday, February 11, 2013 6:24 AM
Friday, February 8, 2013 6:49 PM -
Thanks all!!! my code works correctly now!!!Saturday, February 9, 2013 7:27 AM
-
If you find my answer correctlly, please mark it as answer.
Microsoft Student Parnter Microsoft Technology Associate
Saturday, February 9, 2013 1:07 PM