Can use the AggregateException
to do what you want:
try
{
List<Exception> excepcoes = new List<Exception>();
excepcoes.Add(new ArgumentException("argumento", "argumento invalido"));
excepcoes.Add(new ArgumentNullException("argumento nulo"));
excepcoes.Add(new InvalidCastException("operacao invalida"));
throw new AggregateException(excepcoes);
}
catch(AggregateException aEx)
{
foreach(var ex in aEx.InnerExceptions)
{
Console.WriteLine("{0}: {1}\n", ex.GetType(), ex.Message);
// Output:
// System.ArgumentException: argumento
// Parameter name: argumento invalido
// System.ArgumentNullException: Value cannot be null.
// Parameter name: argumento nulo
// System.InvalidCastException: operacao invalida
}
}
The constructor of AggregateException
accepts a list of exceptions, which can then be accessed through the property .InnerExceptions
.
Behold here an example in dotFiddle.
You don’t want to use
AggregateException
? Can create aAggregateException
with a list of exceptions and then catch theAggregateException
in acatch
and access the exceptions through the.InnerExceptions
.– Omni
A validation method should not make an exception. http://answall.com/q/21767/101 http://answall.com/q/15261/101 http://answall.com/a/56299/101
– Maniero
@Leandro a tip is to be careful about releasing exceptions frequently , depending on what is its validation , because if it is for example validation of a registration and there are frequent errors this can bring down the app pool in IIS , even if the exception is treated . ( IIS understands that this should happen if many exceptions occur )
– John Diego
Thanks for the tip @Johndiego. But in my case is for Windows Form same.
– Leandro