In the following code userexception class defined below is inheriting ApplicationException class. To my knowledge I know base keyword is used to pass the parameter, to parent class constructor. Here ApplicationException is the parent class. If this is the case, I wonder how does the object e of userexception class in the catch block can act as an argument and store the information "Transaction was unuccessful" , though Amount_To_WithDraw is not the parent class for userexception class. I want to know the in and out mechanism happening here when an exception is caught.
class Program
{
static void Main(string[] args)
{
Amount_To_WithDraw A = new Amount_To_WithDraw();
Console.WriteLine("Enter the amount to withdraw");
int cash = Convert.ToInt32(Console.ReadLine());
A.CheckBalance(cash);
Console.Read();
}
}
class userexception : ApplicationException
{
public userexception(string Message)
: base("Transaction was unsuccessful") -> for which class base
refers to here.
{
Console.WriteLine(Message);
}
}
class Amount_To_WithDraw
{
public void CheckBalance(int Amount)
{
int Balance = 1000;
try
{
if ((Balance - Amount) < 500 && (Balance - Amount) > 0)
{
throw new userexception("Least Balance");
}
else if ((Balance - Amount) < 0)
{
throw new userexception("Transaction Leads To Negative Balance");
}
else
Console.WriteLine("Transaction Success");
}
catch (userexception e) -> how can the object e of userexception class
can be considered as an argument for the
parameter sent using base key word
above.
{
Console.WriteLine(e.Message);
}
}
}
Ignore exceptions here. All you're seeing is the equivalent of this:
public class Parent
{
private readonly string message;
public string Message { get { return message; } }
public Parent(string message)
{
this.message = message;
}
}
public class Child : Parent
{
// Just pass the message parameter up to the parent
public Child(string message) : base(message) {}
}
Parent x = new Child("foo");
Console.WriteLine(x.Message);
It's exactly the same. In your case, you're using the Exception.Message
property, which is populated by the message passed up the constructor chain.
It's unfortunate that you've called the parameter Message
in the userexception
constructor - partly because it's unconventional (it should start with m
; your type name ignores naming conventions too), partly because you're not passing it up as the exception message, and partly because it has the same name as the property that you're later fetching.
You might find the whole thing more understandable if you change that constructor to:
public userexception(string message)
: base("Transaction was unsuccessful: " + message)
{
}
Then you'd end up with your caught exception having a Message
property value of:
Transaction was unsuccessful: Least Balance
(or whatever).
See more on this question at Stackoverflow