Overriding the message of exception in C#

Is there a way to override the message of an exception?
I don't want to make a custom exception but to override the message of an existing exception.
For example: Every time when a ArgumentOutOfRangeException is thrown, I'd like it to contain my message instead of the default one.

Is it possible?

Jon Skeet
people
quotationmark

For exceptions you're throwing, you can just pass the message in to the constructor:

throw new ArgumentOutOfRangeException("name", "My custom message");

Note that here, name is the name of the parameter that caused the problem. In C# 6, you should use the nameof operator to make this refactoring-safe:

public void Foo(int x)
{
    if (x > 10)
    {
        throw new ArgumentOutOfRangeException(nameof(x), "That's too big");
    }
}

You can't modify the message of an exception thrown by other code, but you can catch the exception and rethrow another one:

try
{
    ...
}
catch (FooException e)
{
    // Keep the original exception
    throw new BarException("Some message", e);
}

I would try to avoid doing this too much though. If you're considering showing exception messages to users, I would generally shy away from that - they're really aimed at developers. As an example, the ArgumentOutOfRangeException you suggested should generally indicate a bug in your code rather than some external condition (like a network failure or whatever) - the user isn't going to be able to do anything about that bug; it's something you should fix. A network failure or something similar is at least more reasonable for the user to take action about, but frankly it's often not going to be clear what the chain of events is.

people

See more on this question at Stackoverflow