overriding exception message

G

Guest

I wanted to create an exception handler for certain processing I do - but
although I can 'throw' to the constructor with a parameter, I cannot
override the exception message property, the error says its read only. How
can or if a person can create the override ?

class privateException: Exception
{
public privateException(string str)
{
Console.WriteLine("User Defined Exception" +
this.Message+this.StackTrace);
// this.Message=" Special Error " + str
// you cannot seem to create modify the message.
// this input could cause some additional interaction - maybe here
// would be where a file could be written
}
public privateException()
{

}
}
 
C

chris martin

I wanted to create an exception handler for certain processing I do -
but although I can 'throw' to the constructor with a parameter, I
cannot override the exception message property, the error says its
read only. How can or if a person can create the override ?

class privateException: Exception
{
public privateException(string str)
{
Console.WriteLine("User Defined Exception" +
this.Message+this.StackTrace);
// this.Message=" Special Error " + str
// you cannot seem to create modify the message.
// this input could cause some additional interaction -
maybe here
// would be where a file could be written
}
public privateException()
{
}
}


class PrivateException : ApplicationException
{
public PrivateException()
{}

public PrivateException(string message) : base(message)
{}

public PrivateException(string message, Exception innerException) : base(message,
innerException)
{}
}
 
J

Jon Skeet [C# MVP]

andrewcw said:
I wanted to create an exception handler for certain processing I do - but
although I can 'throw' to the constructor with a parameter, I cannot
override the exception message property, the error says its read only. How
can or if a person can create the override ?

class privateException: Exception
{
public privateException(string str)
{
Console.WriteLine("User Defined Exception" +
this.Message+this.StackTrace);
// this.Message=" Special Error " + str
// you cannot seem to create modify the message.
// this input could cause some additional interaction - maybe here
// would be where a file could be written
}
public privateException()
{

}
}

Well, you could override the property:

class PrivateException : Exception
{
string otherMessage;

public PrivateException (string message)
{
otherMessage = message;
}

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

However, you might as well pass the message to the base constructor in
the first place:

class PrivateException : Exception
{
public PrivateException (string message) : base (message)
{
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top