30
Answers

Creating own EXCEPTION CLASSES

Ask a question
Maha

Maha

12y
2.1k
1
This example is given to demonstrate creating your own EXCEPTION CLASSES. I wish to know importance of having static (highlighted in the example)

using System;
public class TryBankAccount
{
public static void Main()
{
BankAccount acct = new BankAccount();

try
{
acct.SetAccountNum(1234);
acct.SetBalance(-1000);
}
catch(Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
}
}
}
//p303
public class BankAccount
{
private int accountNum;
private double balance;

public int GetAccountNum()
{
return accountNum;
}
public void SetAccountNum(int acctNumber)
{
accountNum = acctNumber;
}

public double GetBalance()
{
return balance;
}
public void SetBalance(double bal)
{
if(bal < 0)
{
NegativeBalanceException nbe = new NegativeBalanceException();
throw(nbe);

//OR throw(new NegativeBalanceException());

}
balance = bal;
}
}
public class NegativeBalanceException : ApplicationException
{
private static string msg = "Bank balance is negative.";

public NegativeBalanceException() : base(msg)
{
}
}

/*
Bank balance is negative.
at BankAccount.SetBalance(Double bal) in c:\documents and settings\winuser\my documents\my files\vif\visual c#\visual c# step by step\book chapters assignments\chapter8\dustbin 8\class1.cs:line 46
at TryBankAccount.Main() in c:\documents and settings\winuser\my documents\my files\vif\visual c#\visual c# step by step\book chapters assignments\chapter8\dustbin 8\class1.cs:line 13
Press any key to continue
*/


Answers (30)