问题描述
我想知道正确的方法是通过从一个方法到另一个异常是什么。
I'm wondering what the correct way is to pass on an exception from one method to another.
我工作的一个项目,分为展示(网络),商业和逻辑层,和错误(如的SQLExceptions)需要被流传下来的链出现问题时通知网络层。
I'm working on a project that is divided into Presentation (web), Business and Logic layers, and errors (e.g. SqlExceptions) need to be passed down the chain to notify the web layer when something goes wrong.
我见过的3个基本的方法:
I've seen 3 basic approaches:
try
{
//error code
}
catch (Exception ex)
{
throw ex;
}
(简单地重新抛出)
(simply rethrow)
try
{
//error code
}
catch (Exception ex)
{
throw new MyCustomException();
}
(抛出一个自定义异常,所以在数据提供程序的依赖性不传递)结果
,然后简单地
(throw a custom exception, so that a dependency on the data provider is not passed on)
and then simply
//error code
(没有做任何事情,本身让错误冒泡)
(not doing anything at all, letting the error bubble up by itself)
当然有一些记录在catch块发生了。
Naturally there's some logging happening in the catch block too.
我喜欢3号,而我的同事使用方法1,但我们俩都不能够真正激发为什么。
I prefer number 3, while my colleague uses method 1, but neither of us can really motivate why.
什么是使用各种方法的优点/缺点是什么?有没有更好的方法,我不知道的?有没有一个公认的最佳方式?
What are the advantages/disadvantages of using each method? Is there a better method I don't know of? Is there an accepted Best Way?
推荐答案
如果你什么都不做,你应该简单地让它去上,其中一些人会处理它。
If you do nothing you should simply let it go upper where some one will handle it.
您可以随时处理它的一部分(如日志记录),并重新把它扔。你可以通过简单的发送再次抛出抛出;
,而无需显式的前名
You can always handle a part of it (like logging) and re-throw it. You can re-throw by simply sending throw;
without having to explicit the ex name.
try
{
}
catch (Exception e)
{
throw;
}
的优点来处理它,你可以确保一些机制那里通知你,你有一个错误,你不疑有一个。
The advantage to handle it is that you can ensure that some mechanism is there to notify you that you have an error where you do not suspect to have one.
不过,在某些情况下,我们说一个第三方,你想让用户句柄它时,它的这种情况下,你应该让它继续泡了。
But, in some case, let say a Third Party, you want to let the user handle it and when it's that case you should let it continue to bubble up.
这篇关于什么是传递一个异常的正确方法? (C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!