我在底层方法中的每个方法都有异常处理代码。
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
的区别吗?在这里看一下,并且进行一些谷歌搜索:https://dev59.com/lXA75IYBdhLWcg3w-OZA - MethodMan