开发者

C# exception handling (with a string given to a constructor)

开发者 https://www.devze.com 2023-01-31 17:11 出处:网络
I have a WeekdayException class that has the ToString(). I want to return the string set up in Constructor (\"Illegal weekday: \" + wday) with ToString(). How to access the string?

I have a WeekdayException class that has the ToString(). I want to return the string set up in Constructor ("Illegal weekday: " + wday) with ToString(). How to access the string?

using System;

class WeekdayException : ApplicationException {
    public WeekdayException(String wday) : base("Illegal weekday: " + wday) {}

    public override string ToString()
    {
        return "HELLO" + ???;
    }
}

class TryCatchFinally 
{
    public static void Main(String[] args) 
    {
        try
        {
            throw new WeekdayException("thrown by try");
        }
        catch (ApplicationException ex) 
        {
            Console.WriteLine("Catch ..." + ex.ToString());
        }
    }
}

And is this (making and using ToString()) the method that C# programmers use? If not开发者_运维知识库, what's the way to go?


This is how you can access wday specifically by adding a private member variable (but see below):

class WeekdayException : ApplicationException {
    private readonly string weekday;
    public WeekdayException(String wday) : base("Illegal weekday: " + wday) {
        this.weekday = wday;
    }

    public override string ToString()
    {
        return "HELLO " + this.weekday;
    }
}

And is this (making and using ToString()) the method that C# programmers use? If not, what's the way to go?

Typically for exceptions you set and use the Message property which is set when you invoke the constructor for the base ApplicationException.

class WeekdayException : ApplicationException {
    public WeekdayException(string weekday)
        : base("Illegal weekday: " + weekday) { }
}

Then:

try {
    throw new WeekdayException("Tuesday");
}
catch(WeekdayException weekdayException) {
    Console.WriteLine(weekdayException.Message);
}

Finally, don't abbreviate names like weekday to shorter variants like wday. Just use the full name.


The ApplicationException(string) constructor sets the ApplicationException's Message property, so you should be able to use Message as well.


I recommend you override the Message property:

class WeekdayException : ApplicationException
{
    private readonly string _message;

    public override string Message
    {
        get { return _message; }
    }

    public WeekdayException(String wday)
    {
        _message = "Illegal weekday: " + wday;
    }

    public override string ToString()
    {
        return Message;
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消