Aeoliyan
Aeoliyan

Reputation: 835

How to throw a predefined exception that inform the parameter name, the argument value, and predefined system error message?

Description

If I use the following constructor of ArgumentOutOfRangeException class, the exception will inform the parameter name that causes the exception, along with a predefined system error message:

public ArgumentOutOfRangeException(string paramName)

Alternatively, if I use the following constructor, the exception will inform the parameter name, the argument value, and the specified error message:

public ArgumentOutOfRangeException(string paramName, object actualValue, string message)

Question

How to throw a predefined exception that inform the parameter name, the argument value, along with a predefined system error message?

I'm not confident with this one:

public static int Test(int Number)
{
  ArgumentOutOfRangeException argEx = new ArgumentOutOfRangeException();
  throw ArgumentOutOfRangeException("Number", Number, argEx.Message);
}

Upvotes: 1

Views: 444

Answers (1)

igorc
igorc

Reputation: 2034

Create a custom exception derived from the ArgumentOutOfRangeException and as many parameters as you want.

public class ExtendedArgumentOutOfRangeException : ArgumentOutOfRangeException
{
    public string SystemMessage { get; }

    public ExtendedArgumentOutOfRangeException(string message, string value, string systemMessage) : base(message, value)
    {
        SystemMessage = systemMessage;
        // more here
    }
}

Upvotes: 1

Related Questions