【发布时间】:2012-10-12 11:05:15
【问题描述】:
如果我有一个方法可以检查其参数的有效性,是否可以抛出我自己从System.ArgumentException 派生的自定义异常?我之所以问是因为ArgumentException 本身是从System.SystemException 派生的,而且我看到有关应用程序是否应从SystemException 派生的相互矛盾的指导方针。 (虽然是间接的,从ArgumentException 派生仍然等同于从SystemException 派生。)
我看到很多指导方针说不要从 ApplicationException 派生,而是从 Exception 派生。我对此很满意。我不确定是否也可以从 SystemException 派生。
如果我不应该从SystemException 派生,那么我应该从什么派生我的"invalid argument" 异常类?
【问题讨论】:
-
如果提供的参数无效,该方法应抛出
ArgumentException。您可以完美地从中派生出在这种情况下使用。从SystemException派生没有意义,但如果参数为空,则抛出ArgumentNullException,如果参数超出可接受范围,则抛出ArgumentOutOfRangeException。它们都来自ArgumentException。因此,在这种情况下抛出一个不是从ArgumentException派生的自定义异常是恕我直言,您不应该 做的事情。所以我会选择 Botz3000 的答案。