【发布时间】:2018-11-05 20:40:21
【问题描述】:
应该允许异常的构造函数抛出异常吗?
例子:
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;
}
}
在构造函数中抛出的那些异常(ArgumentNullException 和 ArgumentException)在使用 MyException 时可能会造成伤害?
这是此异常的用例:
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);
}
}
}
}
我所说的危害是:如果由于某些原因使用MyException 的程序员没有检查输入列表(if (lst.Count > 0)),它可能会导致不需要的ArgumentNullException/ ArgumentException.
我认为这可能会导致程序员试图用错误的参数抛出 MyException 却抛出 ArgumentNullException/ArgumentException 的错误。
我应该:
- 不要在
MyException的构造函数中进行检查,而将Errors属性的管理完全由用户管理 - 做检查并抛出
ArgumentNullException/ArgumentException,知道这会导致错误
【问题讨论】:
-
@DaltonCézane OP 正在询问是否专门从 Exception 类的构造函数中抛出异常。您提供的链接通常讨论从构造函数中抛出异常
-
是的,你们都是对的。谢谢你的警告。
-
在构造函数中抛出异常是完全可以接受的,只要它们表明调用者有错误。就你而言,这正是你正在做的事情。
-
@Bruno 在这种情况下也是一样的
-
@Simone - 这看起来不像是链接问题的副本(适用于 Java 而不是 c#),但它确实感觉主要是基于意见的定义,比如 here,因为它是基本上是关于编码标准和最佳实践的问题。需要重新打开吗?
标签: c# exception exception-handling try-catch