Handling an exception inside an exception's constructor?

R

Rick

I have created a custom exception class for my application. In it, I want to
be able to automatically output the ToString() from the object causing the
exception. (I use the ToString() to output the state of my objects to help
with debugging). However, the ToString() method, being often overriden, may
itself cause an exception, in which case a try-catch block does not work.
How can I handle exceptions in this situation... or is this even the right
question? Any other way to achieve this?

public class MyException : ApplicationException
{
public MyException(string message, object source, Exception
innerException)
: base(MakeMessage(message, source), innerException){}

private static string MakeMessage(string message, object source)
{
string Msg = message;
if(source != null)
{
try{Msg = message + " [ SOURCE: " + source.ToString() + " ]";}
catch{Msg = message + " [ Source: " + source.GetType().Name +
" ]";}
}
return Msg;
}
}
 
B

Bruce Wood

What, exactly, do you mean by "doesn't work"? Do you get a compiler
error? Which one? Does it fail at runtime? How?
 
R

Rick

Bruce Wood said:
What, exactly, do you mean by "doesn't work"? Do you get a compiler
error? Which one? Does it fail at runtime? How?

in MakeMessage() it throws an exception and doesn't catch the exception in
the catch() block.
 
R

Rick

Jon Skeet said:
Could you post a short but complete program which demonstrates the
problem?

See http://www.pobox.com/~skeet/csharp/complete.html for details of
what I mean by that.

I created a program which then failed to replicate the issue, which in
itself is a big help. It was a problem that was reported to me, and I saw it
happen with my own eyes on another station (with exception handling
enabled). For now, I have reactived that piece of code and will have to wait
to see if it happens again.

Thanks for your interest in this (Jon and Bruce).
 

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