System.Exception

  • Thread starter Thread starter Ivan A.
  • Start date Start date
I

Ivan A.

Hi

Is there any method to change System. Exception. Message property in derived
exception's constructor? I need runtime class' information to initialize
this property, but it's readonly.

Thaks.
 
Ivan A. said:
Is there any method to change System. Exception. Message property in derived
exception's constructor? I need runtime class' information to initialize
this property, but it's readonly.

Pass it in in the call to the base constructor. For example:

public class FooException : Exception
{
public FooException (string message) : base (message)
{
}
}
 
Hi

Thanx for reply, but base class constructor is called before I can do
something in my own constructor so this is not solution to my problem.
 
Ivan,
In addition to passing it to the constructor, if you are creating a derived
class, you can override the Message property.

Also remember that Exception.Message is intended for user display,
Exception.ToString includes "runtime class' information" by virtue of the
stack trace property.

Hope this helps
Jay
 
Hi

Thanks, I'll try that, but I think it will work!

I found another solution, in constructor of my exception I compute exception
Message and then re-throw the same exception with this message string as
constructor parameter for new exception. So client gets new exception with
proper message property. Is this ok?
 
NO!

I would use the constructor As Jon identified:

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

If you need to "compute" the message to pass to "base (message)" I would
either use a static method to compute the message based to the base or I
would simply override the Message property.

Hope this helps
Jay
 
Ivan A. said:
Thanx for reply, but base class constructor is called before I can do
something in my own constructor so this is not solution to my problem.

If you need to do processing before constructing the message, I suggest
you use a factory method instead - a static method which does the
processing and then creates the exception.
 
I need runtime information of current class' instance so Message property
overloading is what I choosed...
 
Back
Top