There is a statement in a book saying that "Every Exception object contains a ToString() method and a Message field". Message field is obvious this is highlighted in the following program. Please explain what is meant by ToString() method.
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);
}
Console.ReadKey();
}
}
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);
}
balance = bal;
}
}
public class NegativeBalanceException : ApplicationException
{
private static string msg = "Bank balance is negative.";
public NegativeBalanceException() : base(msg)
{
}
}
Loading
Posted Jun 25, 2013, 7:38 PM
VulpesPosted Jun 25, 2013, 12:04 PM
http://msdn.microsoft.com/en-us/library/system.exception.tostring.aspx
Notice, in particular, that it makes use of the Message property and a custom exception class, such as NegativeBalanceException, can therefore customize the error message by passing a suitable message to the base class's constructor.
Sanjeeb LenkaPosted Jun 25, 2013, 11:24 AM
http://www.dotnetperls.com/tostring