需要帮助摆脱异常丛林

时间:2012-04-25 11:06:20

标签: c# .net exception flow-control

我现在已经google了一段时间,我仍然不知道在哪种情况下使用哪个例外。我已经读过在你自己的代码中引发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也不是好习惯,是吗?

2 个答案:

答案 0 :(得分:2)

我确信ArgumentOutOfRangeException是最好的内置例外。 ReSharper也表明了这一点 如果你需要另一个......那么单程就是create the new special exception CommandAppearanceIsNotSpecifiedException

答案 1 :(得分:1)

对于您的示例方案,我建议:

  • ArgumentOutOfRangeException如果方法支持枚举中的所有值,则传递的值无效。
  • NotSupportedException如果方法支持枚举中的值的子集。

一般来说,您希望尽可能使用异常类型See this list of exceptions in the .net framework,这是有意义的,否则您想要自己介绍。这可能涉及为您的应用程序添加一个常见的应用程序异常,并添加从中继承的更具体的应用程序异常。

e.g。

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).
}
相关问题