prosseek
prosseek

Reputation: 191159

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

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?

Upvotes: 1

Views: 414

Answers (3)

jason
jason

Reputation: 241779

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.

Upvotes: 3

ChaosPandion
ChaosPandion

Reputation: 78292

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

Upvotes: 1

Daniel DiPaolo
Daniel DiPaolo

Reputation: 56418

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

Upvotes: 1

Related Questions