C# 需要帮助才能走出异常丛林吗

C# 需要帮助才能走出异常丛林吗,c#,.net,exception,control-flow,C#,.net,Exception,Control Flow,我已经在谷歌上搜索了一段时间,但我仍然不知道在哪个场景中使用哪个异常。我已经读到在您自己的代码中引发SystemExceptions是一种不好的做法,因为这些异常最好由CLR引发 但是,现在我想知道在不同的场景中我应该提出什么Exeption。假设我有一个方法,它以枚举作为参数进行调用。这不是一个很好的例子——它只是从我的脑海中浮现出来的 public enum CommandAppearance { Button, Menu, NotSpecified } //...

我已经在谷歌上搜索了一段时间,但我仍然不知道在哪个场景中使用哪个异常。我已经读到在您自己的代码中引发
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!")
    }
}
这里会是什么?有没有什么网站,我可以在那里得到一个概述?有没有什么模式可以告诉你应该提出什么样的异常?我只需要一些关于这个话题的建议,因为我对这一点很不自信


我认为仅仅提出
newexception()
s也不是好的做法,是吗?

我确信
ArgumentOutOfRangeException
是最好的内置异常。也表明了这一点。

如果你还需要一些。。那么唯一的方法就是
命令外观未指定异常

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

  • ArgumentOutOfRangeException
    如果该方法支持枚举中的所有值,并且传递了无效值
  • NotSupportedException
    如果方法支持枚举中的值的子集
一般来说,您希望尽可能使用异常类型,这是有意义的,否则您希望引入自己的异常类型。这可能涉及为您的应用程序添加一个公共应用程序异常,并添加从中继承的更具体的异常

e、 g


+1仅针对标题:)不建议抛出
new Exception()
,因为方法的调用方必须捕获所有异常类型,而不仅仅是方法抛出的特定异常类型。我实际上使用了ReSharper。此工具建议哪些例外情况?而且,我的目标不仅仅是
ArgumentOutOfRangeException
。我还想知道是否存在一种概述,即在哪种情况下使用哪种异常。我不是说自定义例外。只针对这样的标准场景。我们通常只做
Log.Error(ex);掷骰子
(Caliburn)当您将
开关
运算符与
枚举
参数一起放入并在其主体内设置光标时,ReSharper允许您按
Alt+Enter
并生成
大小写
s。它为
default
分支建议
ArgumentOutOfRangeException
。我建议您从
enum
中删除
NotSpecified
项,因为每个不是
按钮或
菜单的值都意味着
enum
值未指定。正如我所写的,这不是一个很好的示例。这不是我正在使用的实际代码。如果您有一个泛型方法,并且切换
typeof(t)
,并且传递的
t
不受支持,您会使用什么异常?我会使用NotSupportedException,或者如果可能,在方法上添加一个泛型约束,以尽可能将其限制为受支持的类型。
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).
}