C#试图捕获模式的帮助 [英] C# try catch pattern help

查看:94
本文介绍了C#试图捕获模式的帮助的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们总是需要尝试我们的代码捕获它变得丑陋像

We always need to try catch in our code and it becomes ugly like

public void foo()
{
  try
  {
    DoSomething();
  }
  catch(Exception e)
  {
     //do whatever with e
  }
}

public int FooReturnInt()
{
  try
  {
     return IntAfterSomeCalculation();
  }
  catch(Exception e)
  {
    //do exactly whatever with e as foo()
  }
}

想象一下,我们有很多这样的公共职能巨大的类,我们在每一个功能的应用同样的尝试捕捉。

Imagine we have a huge class with many public functions like this and we have to apply same try catch in every single function.

在理想情况下,因为尝试捕捉部分是相同的,我们可以通过下Func键<>作为参数传递给一个辅助功能,它确实像

Ideally, since the try catch part is identical, and we can pass down Func<> as parameter to a helper function which does something like

public void TryCatch(Func<something> theFunction)
{
  try
  {
    theFunction();
  }
  catch(Exception e)
  {
    //processthe common exception        
  }
}

然后,我想这将整理我的代码了很多,现在的问题是如何正确地写这个功能呢?这个函数的返回类型取决于theFunction的返回类型。

Then I'd imagine this would tidy up my code alot, the now the problem is how to properly write this function? The return type of this function is depended on the return type of theFunction.

推荐答案

如果您的真的认为这是需要的,你可以使用:

If you really think this is needed, you could use:

public T TryCatch<T>(Func<T> theFunction)
{
  try
  {
    return theFunction();
  }
  catch(Exception e)
  {
    // You'll need to either rethrow here, or return default(T) etc
  }
}

不过,我一般会建议反对。你真的确定的你所需要的try / catch块在所有这些方法?通常有不该的很多try / catch块,除非渔获只是包装异常,并重新抛出......甚至认为在C#中罕见的比它在Java中,例如。

However, I would generally advise against it. Are you really sure you need the try/catch blocks in all of these methods? Generally there shouldn't be many try/catch blocks unless the catch just wraps the exception and rethrows... and even that's rarer in C# than it is in Java, for example.

您通常应该捕捉异常时,你可以真正的处理的它优雅,或者您需要防止进程炸毁仅仅因为一个请求失败(例如) 。我倾向于写很少catch块 - 这是比较罕见的,我真的可以从错误中恢复:)

You should usually catch an exception when you can either genuinely handle it gracefully or you need to prevent the process from blowing up just because one request failed (for example). I tend to write very few catch blocks - it's relatively rare that I can really recover from errors :)

这方法将导致显著困难的时间调试,我疑似。它的可以的仍然是值得做的,但您应该谨慎考虑利弊第一。

This approach is going to lead to a significantly harder time debugging, I suspect. It may still be worth doing, but you should carefully consider the pros and cons first.

这篇关于C#试图捕获模式的帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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