如果我有这样的东西怎么办:
public static void DoSomething()
{
try
{
//some code
try
{
//some other code
}
catch (Exception e)
{
log.Error("At the end something is wrong: " + e);
FunctionA(); //same function as in the first exception
}
}
catch (Exception e)
{
log.Error("At the start something wrong: " + e);
FunctionA();
}
}
所以我有一个尝试在另一个。异常应该是不同的,我想用不同的记录器来处理它们。但假设我想为这两个异常调用相同的函数。我必须写两次FunctionA()
。这样可以吗?或者这种类型的异常还有其他问题吗?建议?
您可以使用单个try块和多个catch块;此外,无论是否出现异常,都可以使用finally语句来执行某些代码段。
在函数中使用多个try-catch块通常不是一个好主意。此外,最好在发生异常的位置处理异常。
public static void DoSomething()
{
try
{
//some code
}
catch (ExceptionA e)
{
// exception is ExceptionA type
log.Error("At the end something is wrong: " + e);
FunctionA(); //same function as in the first exception
}
catch (ExceptionB e)
{
// exception is ExceptionB type
log.Error("At the start something wrong: " + e);
FunctionA(); //same function as in the first exception
}
finally
{
//you can do something here whether there is an exception or not
}
}
因此,您希望在所有异常情况下调用一个方法。然后,如果全部成功执行,我将使用Boolean
变量来存储。然后你可以在最后相应地调用FunctionA
:
public static void DoSomething()
{
bool success = true;
try
{
//some code
try
{
//some other code
} catch (Exception ex)
{
success = false;
try
{
//some other code
} catch (ExceptionA eA)
{
log.Error("At the end, something went wrong: " + eA);
} catch (ExceptionB eB)
{
log.Error("At the end, something else went wrong: " + eB);
}
}
} catch (Exception ex)
{
success = false;
log.Error("At the start something wrong: " + ex);
}
if(!success)
FunctionA();
}
但是,如果您在任何情况下都想调用此方法,这意味着无论是否引发异常,都可以使用finally
。如果您想清理资源,它也很有用。
您可以将代码放入可重用的方法中,例如
public void LogIfSomeException(Action action, string message)
{
try
{
action();
}
catch (SomeException e)
{
log.Error(message + e);
FunctionA();
}
}
你可以像这样使用:
public static void DoSomething()
{
LogIfSomeException(() => {
// start code
LogIfSomeException(() => {
// end code
}, "At the end something is wrong");
}, "At the start something is wrong");
}
如果您更改DoSomthing
以重新抛出这样的异常,
public static void DoSomething()
{
try
{
//some code
try
{
//some other code
}
catch (Exception e)
{
log.Error("At the end something is wrong: " + e);
throw;
}
}
catch (Exception e)
{
log.Error("At the start something wrong: " + e);
throw;
}
}
这是有道理的,因为记录异常并不是真正处理它,我怀疑FunctionA
是否会这样做,但。当您调用DoSomething
时,您可以捕获任何一个异常。
static void CallDoSomething()
{
try
{
DoSomething();
}
catch
{
FunctionA();
}
}
或者,如果你真的想在同一个函数中执行它。
public static void DoSomething()
{
try
{
try
{
// some code
try
{
// some other code
}
catch (Exception e)
{
log.Error("At the end something is wrong: " + e);
throw;
}
}
catch (Exception e)
{
log.Error("At the start something wrong: " + e);
throw;
}
}
catch (Exception) // I include the type in the hope it will be more derived.
{
FunctionA();
}
}