异常处理:用户定义的异常:

时间:2015-02-26 14:58:09

标签: c#-4.0

在下面的代码中,下面定义的userexception类继承了ApplicationException类。据我所知,我知道base关键字用于将参数传递给父类构造函数。这里ApplicationException是父类。如果是这种情况,我想知道catch块中userexception类的对象e如何充当参数并存储信息“Transaction was unuccessful”,尽管Amount_To_WithDraw不是userexception类的父类。我想知道捕获异常时在这里发生的进出机制。

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);
        }
    }
}

1 个答案:

答案 0 :(得分:1)

忽略此处的例外情况。你所看到的就等同于:

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);

它的完全相同。在您的情况下,您使用Exception.Message属性,该属性由在构造函数链中传递的消息填充。

很遗憾,您在Message构造函数中调用了参数 userexception - 部分原因是它非常规(它应该是以m开头;您的类型名称也忽略了命名约定),部分原因是您并未将其作为异常消息传递,部分原因是它与您所属的属性具有相同的名称后来取材。

如果将构造函数更改为:

,您可能会发现整个事情更容易理解
public userexception(string message)
    : base("Transaction was unsuccessful: " + message)
{
}

然后,您最终会遇到Message属性值为{<1}}的被捕异常。

Transaction was unsuccessful: Least Balance

(或其他)。