[英]C# what kind of exception should I raise?
我目前正在试图找到一个属性是否已正确设置为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'类型的异常,这是一种异常类型,具体程度不够,用户代码永远不应该引发。如果可能抛出此异常实例,请使用其他异常类型。
Soooo我应该抛出什么异常,这对于Microsoft ..来说是特定的,因为在我自己的应用程序的逻辑处理和我想“抛出”时抛出错误的情况。
ArgumentException
InvalidOperationException
FormatException
传递的论点并不好。
你应该抛出一个例外吗?
具有错误的布尔值并不是特殊情况。
编辑
我原来的答案有点简洁,所以我会详细说明......
从您的示例中,不清楚实际对象,属性和方法代表什么。 如果没有这些信息,很难说出哪种类型的例外(如果有的话)是合适的。
例如,我认为以下是对异常的完全有效使用(并且您的真实代码可能看起来像这样,但我们无法从您的示例中得知):
public void UpdateMyCustomType(MyCustomType customType)
{
if (!customType.IsUpdateable)
throw new InvalidOperationException("Object is not updateable.");
// customType is updateable, so let's update it
}
但是在一般情况下,如果不了解你的域模型,我会说像这样的东西(一个错误的布尔值)并不是特别的。
创建自己的异常扩展Exception
。 例如: RuleViolationException
可能是ArgumentException
?
也可以为InvalidOperationException
一个案例。
这里的答案是你不应该抛出任何异常。 为什么抛出异常只是为了在一秒钟内再次捕获它并重新抛出它?
其他答案很适合快速解决,但理想情况下,如果你在编译时知道永远不应该使用某些参数调用某个方法,你可以通过继承你的自定义类型来防止这种情况发生,只有当自定义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中 。
我认为你应该避免代码逻辑的异常。
我建议修改你的方法以将方法的结果作为bool
类型返回,然后你可以决定在调用方法时向用户显示错误消息的适当方法:
public bool RunBusinessRule(MyCustomType customType)
{
try
{
if (customType.CustomBoolProperty == true)
{
DoSomething();
return true;
}
return false;
}
catch(Exception)
{
throw;
}
}
稍微一点,但你可以稍微简化你的代码......
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();
}
至于要抛出的异常类型,您可以考虑使用ApplicationException
或InvalidOperationException
,也可以定义自己的异常类型。
我知道一个问题是关于抛出异常,但我认为在这里做一个断言更合适:
// Precondition: customType.CustomBoolProperty == true
System.Diagnostics.Debug.Assert(customType.CustomBoolProperty)
DoSomething();
InvalidArgument异常很好但更好的是ApplicationException。
通过扩展System.Exception并抛出它来创建自己的自定义异常。 如果你愿意,你可以变得更加疯狂并拥有一整套异常类型。
您可以创建一个仅用于业务逻辑验证的自定义ValidationException
。 或者,您可以为每种类型的验证错误创建单独的验证异常,尽管这可能是过载。
不是你要求的,但是有很多人已经给出了我同意的答案,但是你也应该避免使用catch(Exception ex)。
尝试捕获可能的特定异常是一种更好的做法,如果需要,捕获通用的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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.