[英]When to throw an exception and when to handle issue elegantly
Lets say I have this code: 可以说我有以下代码:
public void MyMethod(string Data, List<string> InputData)
{
//I would assume throwing an exception for nulls would be correct
if (String.IsNullOrWhiteSpace(Data) || InputData == null)
throw new ArgumentNullException("Oops");
if (InputData.Count == 0)
//throw exception or use event to raise a problem
//throw Exception("Empty List")
//if (DisplayError != null)
// DisplayError("Empty List");
}
Now having a empty list is not an exceptional problem so I should cope with it elegantly. 现在有一个空列表不是一个例外的问题,所以我应该优雅地处理它。 One way is to raise an event to notify the problem.
一种方法是引发事件以通知问题。 Just makes me wonder why I dont just raise the event if the arguments are null.
只是让我想知道,如果参数为null,为什么我不只是引发事件。
What is the best practice in this type of issue? 此类问题的最佳做法是什么?
EventHandler Example: EventHandler示例:
public class MyOtherClass
{
public event Action<string,List<string>> ItFired;
public void DoSomething()
{
if(ItFired != null)
ItFired(myString, myList);
}
}
public class AnotherClass
{
public void DoSomething()
{
var otherclass = new MyOtherClass();
var myClass = new MyClass();
otherClass.ItFired += myClass.MyMethod;
}
}
If an empty list
is not exceptional problem do not raise exception in that case. 如果
empty list
不是特殊问题, 则在这种情况下不要引发异常 。 Exceptions
are for exceptional cases. Exceptions
是例外情况。 In this case you can just return some boolean
(say) value, that indicates that function is not executed. 在这种情况下,您可以仅返回一些
boolean
(例如),表明该函数未执行。
If for the caller
of that function that would be an exceptional case, then it (caller) will raise an exception. 如果对于该函数的
caller
来说是例外情况,则它(调用者)将引发异常。
Good luck. 祝好运。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.