blah blah blah is here! blah blah » Close

up0down
link

What is the best way to set the default message if I were to create a new exception class?
I will be deriving from the System.IO.IOException exception which will be used if a file in not in a specified format. The default message is "I/O error occurred." but I wanted to change it. I was thinking of overriding all of the constructors but there has to be a more simpler way to do it right?

last answered 2 years ago

1 answers

up0down
link

Well, I suppose you could just override the Message property:
public override string Message
{
get {return "Custom message for I/O error";}
}
Having said that, if you just wanted to have the one parameterless constructor, then it's just as easy to do this;
public MyIOException(): base("Custom message for I/O error")
{
}
This also has the merit of setting the internal _message field in System.Exception, which the first approach doesn't (and can't) do, just in case this field is accessed by other methods/properties or by the system.

up0down
link

Oh right, most of the useful constructors takes in a message parameter. I only have to worry about the default constructor. I was worried about the constructors that didn't take in a message parameter but there aren't any. hah
Overriding the Message property doesn't really change the exception's message, I just stuck with calling one of the base constructors (as you pointed out). Thanks.

This post was imported from csharpfriends, if you have a similiar question please ask it again.

All previous members have been migrated, hope you enjoy the new platform!

Feedback