【发布时间】:2015-06-25 20:32:48
【问题描述】:
对于底层方法的以下代码,我在每个方法中都有异常处理代码
throw new Exception("The error that happens");
有什么办法可以避免在每种方法中一次又一次地编写这段代码?
我正在尝试编写自己的代码,而不是使用任何日志框架
private void TopLevelMethod()
{
try
{
SomeMethod();
}
catch (Exception ex)
{
// Log/report exception/display to user etc.
}
}
private void SomeMethod()
{
TestPartA();
TestPartB();
TestPartC();
TestPartD();
}
private void TestPartA()
{
// Do some testing...
try
{
if (somethingBadHappens)
{
throw new Exception("The error that happens");
}
}
catch (Exception)
{
// Cleanup here. If no cleanup is possible,
// do not catch the exception here, i.e.,
// try...catch would not be necessary in this method.
// Re-throw the original exception.
throw;
}
}
private void TestPartB()
{
// No need for try...catch because we can't do any cleanup for this method.
if (somethingshappens)
{
throw new Exception("The error that happens");
}
}
【问题讨论】:
-
你知道
throw & throw new和throw & throw new之间的区别吗?看看这里以及谷歌搜索stackoverflow.com/questions/2999298/… -
谢谢。我知道了。我正在尝试使用任何集中管理器寻找一些用于异常管理的良好设计模式。
-
创建您自己的处理异常等的自定义类。对于应用程序来说,这在本质上就一些好的设计模式而言是相当固执的,但这只是我的看法。..
-
只是一个意见:与其在方法中抛出异常,不如构建返回布尔值(成功或失败)并更新错误字符串或错误容器(例如 List
)的函数。您将在调试模式下看到这种方法的好处,这种方法只会在意外异常时中断。 -
Graggito: 请给出示例代码示例。谢谢....
标签: c# .net design-patterns