从您的方法返回异常是不好的做法 [英] Is it bad practice to return Exceptions from your methods

查看:142
本文介绍了从您的方法返回异常是不好的做法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的同行已经编写的很多代码库方法通常通过捕获,通知和记录来执行自己的错误处理。



在这些情况下,方法返回一个布尔值,表示成功或失败。



有时候,如果方法失败,我希望调用代码知道为什么,返回一个布尔值是不够的。 p>

有一种方法是在方法中保持错误处理,但使方法为void,并将方法抛出异常。



然而,最近我有习惯通过适当的方法返回异常,通常是否则可以是无效的动作方法,但是我想知道动作的状态。



将异常返回为一个void方法抛出异常的优点是,我认为它使得其他程序员更容易使用您的库,而更重要的是意味着您可以安全地调用该方法而不需要havin g担心捕获异常



例如,如果方法是无效的,程序员应该处理成功或失败可能并不明显。



但是如果方法专门指定了一个返回类型的异常,那么你知道你可以检查成功或失败。但这也意味着你不需要担心如果不想要抓住错误。



这是否有意义?也许我没有使用最好的例子,但是一般来说,返回异常还是有更好的模式吗?



欢呼声



更新



哇,压倒性的结果是方式即可。我是这么想的。我必须说,这样做(返回异常)有点解决了一个问题,但确实感到错误。



所以,从你的一些答案,这些具体方案(复杂类或具有一个或多个外部依赖关系的类(即Web服务))的最佳解决方案似乎是自定义结果类?



更新:



他们真的赞赏所有的意见,正在阅读所有内容,我正在仔细考虑所有的输入



目前我赞成使用一个void方法,抛出异常,然后在外面捕捉....更好?



cheers

解决方案

如果你的意思是...

  public Exception MyMethod(string foo)
{
if(String.IsNullOrEmpty())
{
返回新的ArgumentNullException(foo);
}
}

...而不是...


  public void MyMethod(string foo)
{
if(String.IsNullOrEmpty())
{
throw new ArgumentNullException(foo)
}
}

那绝对不是,这样做不行。您将完全重新发明异常的目的,并将其用作hresult。以下是一些标准的最佳做法



另一个很好的理由是标准代理不再符合您的方法签名。所以,例如,你不能再在MyMethod上使用 Action< string> ,需要使用 Func< string,Exception> 而不是。



@Andy,每个评论,回答太久的评论:不是真的。不要那么关心呼叫者。他的设计应该是防守的。考虑异常的语义...这个应用程序的执行将停止在这里,除非有人知道该怎么做这个问题。如果您可以解决问题,您应该解决这个问题。如果你不能,你必须登录并将其扔到一个新的水平,因为他们可能会知道该做什么。



你应该处理你可以处理的并抛出你不能。根据定义,电话堆栈的人比你有更广泛的世界观。您的应用程序需要有弹性才能处理异常并继续进行。他们只有这样做才是防御性编码,并将问题推到更高层次的信息上,看是否可以做到。



如果答案结束,是否,然后记录问题就可以理解,成为一个好的公民的盒子,并优雅地终止申请,并活下去打一天。不要自私,试图隐藏你的呼叫者的错误。要防守,他也会这样做。 :)



查看企业库异常处理块。它认为他们真正阐述了如何处理整个架构中的异常的伟大愿景。


A lot of the code base methods my peers have written perform their own error handling, usually by catching, notifying, and logging.

In these cases the methods return a boolean, indicating success or failure.

Sometimes though, if a method fails, I want the calling code to know why, and returning a boolean is not enough.

One way around this is to keep the error handling in the methods, but make the method void, and have the methods throw their Exceptions.

However, recently I've got into the habit of returning Exceptions in appropriate methods, usually action methods that could otherwise be void, but where I'd like to know the status of the action.

The advantages of returning an Exception over having a void method throw an Exception is that I think it makes it easier for other programmers to use your library, and, more importantly, it means you can safely call that method without having to worry about catching the Exception

For example, if the method is just void, it might not be instantly obvious that the programmer should handle success or failure.

But if the methods specifically specifies a return type of Exception, then you know you can check success or failure if you want to. But it also means you don't need to worry about catching the error if you don't want to.

Does that make sense? Maybe I haven't used the best example, but generally, is it OK to return Exceptions, or is there a better pattern out there?

cheers

UPDATE

wow, the overwhelming result is no way. I thought so. I must say, doing it (returning an Exception) kinda solved a problem, but it did feel wrong.

So, from some of your answers, the best solution to these specific scenarios (a complex class, or a class with one or more external dependencies (i.e. web service)) seems to be a custom results Class?

UPDATE:

hey guys, really appreciating all the opinions, am reading through everything, and I'm thinking carefully about all the input.

Currently I'm favoring having a void method, throwing the Exceptions, and then catching them on the outside....is that better?

cheers

解决方案

If you mean something like ...

public Exception MyMethod( string foo )
{
   if( String.IsNullOrEmpty() )
   {
      return new ArgumentNullException( "foo" );
   }
}

... rather than ...

public void MyMethod( string foo )
{
   if( String.IsNullOrEmpty() )
   {
      throw new ArgumentNullException( "foo" )
   }
}

Then absolutely not, it is not okay to do that. You would be completely re-inventing the purpose of an exception and using it as an hresult. Here are some standard best practices.

Another good reason not to is that standard delegates would no longer match your method signature. So, for example, you could not use Action<string> on MyMethod anymore and would need to use Func<string,Exception> instead.

@Andy, per comment, answer too long for a comment: Not really. Don't be so concerned about the caller. He should be being defensive in his design anyway. Think about the semantics of an Exception ... "The execution of this application will stop right here unless somebody knows what to do about this problem." If you can resolve the issue, you should resolve it. If you can't, you have to log it and throw it to the next level, because they may know exactly what to do.

You should handle what you can handle and throw what you can't. By definition, the guy up the call stack has a broader view of the world than you. Your application needs to be resilient in it's ability to deal with exceptions and keep on going. They only way to do that is defensive coding and push issues up to higher levels of information to see if anything can be done.

At the end of the day if the answer is "no", then log the problem to it can be understood, be a good citizen of the box and terminate the application gracefully and live to fight another day. Don't be selfish and try and hide errors for your caller. Be defensive and he will do the same. :)

Check out the Enterprise Library Exception handling block. It think they really articulate a great vision for how to deal with exceptions throughout your architecture.

这篇关于从您的方法返回异常是不好的做法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆