再扔无参数的渔获物和没做什么区别? [英] The difference between re-throwing parameter-less catch and not doing anything?

查看:99
本文介绍了再扔无参数的渔获物和没做什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下两类在两个不同的组件:

Suppose I have the following two classes in two different assemblies:

//in assembly A
public class TypeA {
   // Constructor omitted
   public void MethodA
   {
     try {
       //do something
     }
     catch {
        throw;
     }
   }
}
//in assembly B
public class TypeB {
   public void MethodB
   {
     try {
       TypeA a = new TypeA();
       a.MethodA();
     }
     catch (Exception e)
       //Handle exception
     }
   }
}

在这种情况下,在try-catch在治法只是提升了异常,但并没有真正处理它。有没有在治法使用的try-catch都什么优势?换句话说,有没有这样的try-catch块,而不是使用一个在所有有区别吗?

In this case, the try-catch in MethodA just elevates the exception but doesn't really handle it. Is there any advantage in using try-catch at all in MethodA? In other words, is there a difference between this kind of try-catch block and not using one at all?

推荐答案

在您的例如,没有优势于此。但在有些情况下最好是刚泡了一个特定的异常情况。

In your example, there is no advantage to this. But there are cases where it is desirable to just bubble up a specific exception.

    public void Foo()
    {
        try
        {
            // Some service adapter code

            // A call to the service
        }
        catch (ServiceBoundaryException)
        {
            throw;
        }
        catch (Exception ex)
        {
            throw new AdapterBoundaryException("some message", ex);
        }
    }

这使您可以轻松识别边界发生异常英寸在这种情况下,你需要确保你的边界异常抛出仅针对特定的边界代码。

This allows you to easily identify which boundary an exception occurred in. In this case, you would need to ensure your boundary exceptions are only thrown for code specific to the boundary.

这篇关于再扔无参数的渔获物和没做什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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