The constructor of an exception should be allowed to throw exceptions?
Example:
public class MyException : Exception
{
public List<string> Errors { get; private set; }
public MyException(List<string> errors)
{
if(errors == null)
{
throw new ArgumentNullException();
}
else if(errors.Count == 0)
{
throw new ArgumentException("At least one error must be present");
}
Errors = errors;
}
}
Those exceptions (ArgumentNullException
and ArgumentException
) thrown in the constructor can do harm while using MyException
?
This is use case of this exception:
class Program
{
private static void ErrorHandling()
{
List<string> lst = new List<string>();
// ... here do some checks and insert the errors in the list 'lst'
// This check prevent the ArgumentNullException and
// the ArgumentException to be thrown
if (lst.Count > 0)
{
throw new MyException(lst);
}
}
static void Main(string[] args)
{
try
{
ErrorHandling();
}
catch(MyException e)
{
foreach(string s in e.Errors)
{
Console.WriteLine(s);
}
}
}
}
The harm I talk about is: if for some reasons the programmer that use MyException
doesn't check the input list (if (lst.Count > 0)
) it can lead to an unwanted ArgumentNullException
/ArgumentException
.
I think this can lead to bugs where the programmer is trying to throw MyException
with wrong parameters but instead it throw an ArgumentNullException
/ArgumentException
.
Should I:
- Don't do checks in the constructors of the
MyException
and leave the managment of theErrors
property entirely by the user - Do the checks and throw
ArgumentNullException
/ArgumentException
, knowing that this can lead bugs