4

我已经用谷歌搜索了一段时间,但我仍然不知道在哪种情况下使用哪个异常。我读过SystemExceptions在自己的代码中引发是不好的做法,因为这些异常最好由 CLR 引发。

但是好吧,现在我想知道Exeption在不同的情况下我应该提出什么。假设我有一个使用枚举作为参数调用的方法。这不是一个很好的例子——它只是从我的脑海中浮现出来。

public enum CommandAppearance
{
    Button,
    Menu,
    NotSpecified
}

//...

public void PlaceButtons(CommandAppearance commandAppearance)
{
    switch(commandAppearance)
    {
        case CommandAppearance.Button:
            // do the placing
        case CommandAppearance.Menu:
            // do the placing
        case CommandAppearance.NotSpecified:
            throw ArgumentOutOfRangeException("The button must have a defined appearance!")
    }
}

这里会是什么?是否有某种网站,我可以在其中获得概述?是否有任何模式可以告诉您要提出什么样的异常?我只需要一些关于这个主题的提示,因为我对此很不自信。

我认为只加注new Exception()s 也不是好习惯,是吗?

4

2 回答 2

2

我敢肯定ArgumentOutOfRangeException这是最好的内置例外。ReSharper也建议这样做。
如果您需要另一个..那么唯一的方法是创建新的特殊异常 CommandAppearanceIsNotSpecifiedException

于 2012-04-25T11:13:09.450 回答
1

对于您的示例场景,我建议:

  • ArgumentOutOfRangeException如果该方法支持枚举中的所有值并且传递了无效值。
  • NotSupportedException如果该方法支持枚举中值的子集。

一般来说,您希望使用异常类型尽可能在 .net 框架中查看此异常列表,这很有意义,否则您想引入自己的异常类型。这可能涉及为您的应用程序添加一个常见的应用程序异常,并添加从它继承的更具体的异常。

例如

public class MyAppException : Exception
{
    // This would be used if none of the .net exceptions are appropriate and it is a 
    // generic application error which can't be handled differently to any other 
    // application error.
}

public class CustomerStatusInvalidException : MyAppException
{
    // This would be thrown if the customer status is invalid, it allows the calling
    // code to catch this exception specifically and handle it differently to other 
    // exceptions, alternatively it would also be caught by (catch MyAppException) if 
    // there is no (catch CustomerStatusInvalidException).
}
于 2012-04-25T11:24:30.643 回答