C#我应该提出什么样的例外?

我目前正在试图找到一个属性是否已正确设置为bool值,它应该是这样的……

public void RunBusinessRule(MyCustomType customType) { try { if (customType.CustomBoolProperty == true) { DoSomething(); } else { throw new Exception("This is obviously false or possibly null lets throw up an error."); } } catch(Exception) { throw; } } 

现在为我抛出这个错误的处理是我正在使用微软的源代码分析它给我一个错误,说明“CA2201:Microsoft.Usage:Object.RunBusinessRule(MyCustomType)创建了一个’exception’类型的exception,这是一种exception类型,具体程度不够,用户代码永远不应该引发。如果可能抛出此exception实例,请使用其他exception类型。

Soooo我应该抛出什么exception,这对于Microsoft来说是特定的…,因为抛出关于我自己的应用程序的逻辑处理的错误以及当我想“抛出”时。

 ArgumentException InvalidOperationException FormatException 

传递的论点并不好。

你应该抛出一个例外吗?

具有错误的布尔值并不是特殊情况。

编辑

我原来的答案有点简洁,所以我会详细说明……

从您的示例中,不清楚实际对象,属性和方法代表什么。 没有这些信息,很难说出什么类型的例外(如果有的话)是合适的。

例如,我认为以下是对exception的完全有效使用(并且您的真实代码可能看起来像这样,但我们无法从您的示例中得知):

 public void UpdateMyCustomType(MyCustomType customType) { if (!customType.IsUpdateable) throw new InvalidOperationException("Object is not updateable."); // customType is updateable, so let's update it } 

但是在一般情况下,如果不了解你的域模型,我会说像这样的东西(一个假的布尔值)并不是特别的。

创建自己的exception扩展Exception 。 例如: RuleViolationException

可能是ArgumentException

也可以为InvalidOperationException一个案例。

这里的答案是你不应该抛出任何exception。 为什么抛出exception只是为了在一秒钟内再次捕获它并重新抛出它?

稍微一点,但你可以稍微简化你的代码……

 public void RunBusinessRule(MyCustomType customType) { if (customType.CustomBoolProperty == false) { throw new Exception("This is obviously false or possibly null lets throw up an error."); } DoSomething(); } 

至于要抛出的exception类型,您可以考虑使用ApplicationExceptionInvalidOperationException ,也可以定义自己的exception类型。

我知道一个问题是关于抛出exception,但我认为在这里做一个断言更合适:

 // Precondition: customType.CustomBoolProperty == true System.Diagnostics.Debug.Assert(customType.CustomBoolProperty) DoSomething(); 

InvalidArgumentexception很好,但更好的是ApplicationException。

其他答案很适合快速解决,但理想情况下,如果你在编译时知道永远不应该使用某些参数调用某个方法,你可以通过inheritance自定义类型来防止这种情况发生,只有当自定义bool是是的,现在你的方法看起来像。

 public void RunBusinessRule(MyInheritedType inheritedObject) { //No need for checks, this is always the right type. //As a matter of fact, RunBusinessRule might even belong to MyInheritedType. } 

这是我在SOLID中 。

我认为你应该避免代码逻辑的exception。

我建议修改你的方法以将方法的结果作为bool类型返回,然后你可以决定在调用方法时向用户显示错误消息的适当方法:

 public bool RunBusinessRule(MyCustomType customType) { try { if (customType.CustomBoolProperty == true) { DoSomething(); return true; } return false; } catch(Exception) { throw; } } 

通过扩展System.Exception并抛出它来创建自己的自定义exception。 如果你愿意的话,你可以变得更加疯狂并拥有一整套exception类型。

您可以创建一个仅用于业务逻辑validation的自定义ValidationException 。 或者,您可以为每种类型的validation错误创建单独的validationexception,尽管这可能是过载。

不是你要求的,但是有很多人已经给出了我同意的答案,但是你也应该避免使用catch(Exception ex)。

尝试捕获首先可能的特定exception是一种更好的做法,如果需要,捕获通用的Expception。 例如:

 try{ MyMethod(obj); }catch (NullReferenceException ne){ //do something } catch(UnauthorizedAccessException uae){ //do something else } catch(System.IO.IOException ioe){ //do something else } catch(Exception){ //do something else }