Home > Net >  How to get multiple exception for multiple parameters in c#
How to get multiple exception for multiple parameters in c#

Time:03-01

I am trying to get different exceptions (ArgumentOutOfRangeException) depending on different parameters in a method. The CheckParametersAndThrowException3 method checks if unit I and doubled are in the range. The problem for me I only get the exception for int I but not for the 2nd parameter d.Please let me know How can I get exceptions for both the parameters.

  public static bool CheckParametersAndThrowException3(uint i, double d)
    {

        if ((i >= 0 && i < 5) && (d < 1.0 && d >= -1.0))
        {
            return true;
        }
        else
        {
            throw new ArgumentOutOfRangeException(nameof(i), "i should be in [0, 5) interval.");
            throw new ArgumentOutOfRangeException(nameof(d), "d should be in [-1.0, 1.0] interval.");
        }
    }

CodePudding user response:

In your example, the second exception will never be thrown.

Try this:

    static bool CheckRange1 (int x, double y)
    {
        (bool xOK, string xName, string xMsg) = x >= 0 && x < 5 ? (true, "", "") : (false, "x", "x should be in [0, 5)");
        (bool yOK, string yName, string yMsg) = y >= -1.0 && y <= 1.0 ? (true, "", "") : (false, "y", "y should be in [-1.0, 1.0]");
        if (xOK && yOK)
        {
          return true;
        }
        string separator = "";
        if (!xOK && !yOK) 
        {
          separator = ", ";
        }
        throw new ArgumentOutOfRangeException(xName   separator   yName, xMsg   separator   yMsg);
    }

Or without throwing an exception:

static (bool ok, string msg) CheckRange2(int x, double y)
{
    (bool xOK, string xMsg) = x >= 0 && x < 5 ? (true, "") : (false, "x should be in [0, 5)");
    (bool yOK, string yMsg) = y >= -1.0 && y <= 1.0 ? (true, "") : (false, "y should be in [-1.0, 1.0]");
    if (xOK && yOK)
    {
        return (true, "");
    }
    return (false, xMsg   (!xOK && !yOK ? ", " : "")   yMsg);
}

CodePudding user response:

You should just create not throw your two exceptions then throw AggregateException with them

Like this

public static void Main(string[] args)
{
    var firstEx = new ArgumentOutOfRangeException("error msg 1");
    var secondEx = new ArgumentOutOfRangeException("error msg 2");
    throw new AggregateException(firstEx, secondEx);
}

When debugging, exception will look like this (note InnerExceptions property) aggregateExceptionOnDebugging

  • Related