How can i change the Message of an Exception object in C#?
Bonus Chatter
The Message property of Exception is read-only:
public virtual string Message { get; }
Additional Reading
The same question, in PHP, was answered, “You can’t”, but gave a workaround:
You can however determine it’s class name and code, and throw a new one, of the same class, with same code, but with different message.
How can i determine an exception’s class name, and throw a new one of the same class, but with a different message, in C#?
e.g.:
catch (Exception e)
{
Exception e2 = Activator.CreateInstance(e.GetType());
throw e2;
}
doesn’t work because the Message property of an exception is read-only and .NET. See original question.
Update
i tried catching each type of exception i expect:
try
{
reader.Read();
}
catch (OleDbException e)
{
throw new OleDbException(e, sql);
}
catch (SqlException e)
{
throw new SqlException (e, sql);
}
catch (IBM.DbException e)
{
throw new IBM.DbException(e, sql);
}
catch (OdbcException e)
{
throw new OdbcException (e, sql);
}
catch (OracleException e)
{
throw new OracleException (e, sql);
}
Except that now my code forces a dependency on assemblies that won’t be present in every solution.
Also, now the exception seems to come from my code, rather than the line that threw it; i lose the exception’s location information
i found the solution in a blog post linked from a news site:
It’s not perfect (you lose your stack trace); but that’s the nature of .NET.