获取抛出的异常在finally块
-
20-09-2019 - |
题
有没有一种方法,如何让当前抛出的异常(如果存在)?
我想减少代码量和应用一些重用的任务是这样的:
Exception thrownException = null;
try {
// some code with 3rd party classes, which can throw unexpected exceptions
}
catch( Exception exc ) {
thrownException = exc;
LogException( exc );
}
finally {
if ( null == thrownException ) {
// some code
}
else {
// some code
}
}
和与此代码替换:
using( ExceptionHelper.LogException() ) {
// some code with 3rd party classes, which can throw unexpected exceptions
}
using( new ExceptionHelper { ExceptionAction = ()=> /*some cleaning code*/ } ) {
// some code with 3rd party classes, which can throw unexpected exceptions
}
public class ExceptiohHelper : IDisposable {
public static ExceptionHelper LogException() {
return new ExceptionHelper();
}
public Action SuccessfulAction {get; set;}
public Action ExceptionAction {get; set;}
public void Dispose() {
Action action;
Exception thrownException = TheMethodIDontKnow();
if ( null != thrownException ) {
LogException( thrownException );
action = this.ExceptionAction;
}
else {
action = this.SuccessfulAction;
}
if ( null != action ) {
action();
}
}
}
时,这种情况下更多钞票?
由于
解决方案
你有什么考虑以下。而不是在问题看上去“如何获得的最后一个异常?”,如果你将其更改为“我如何运行的一些片的一些更多的控制码?”
例如: 取而代之的ExceptionHelper的你可以有一个ActionRunner。
public class ActionRunner
{
public Action AttemptAction { get; set; }
public Action SuccessfulAction { get; set; }
public Action ExceptionAction { get; set; }
public void RunAction()
{
try
{
AttemptAction();
SuccessfulAction();
}
catch (Exception ex)
{
LogException(ex);
ExceptionAction();
}
}
private void LogException(Exception thrownException) { /* log here... */ }
}
这将至少给你SuccessfulAction的一些重用和ExceptionAction假设只有AttemptAction通话之间变化。
var actionRunner = new ActionRunner
{
AttemptAction = () =>
{
Console.WriteLine("Going to throw...");
throw new Exception("Just throwing");
},
ExceptionAction = () => Console.WriteLine("ExceptionAction"),
SuccessfulAction = () => Console.WriteLine("SuccessfulAction"),
};
actionRunner.RunAction();
actionRunner.AttemptAction = () => Console.WriteLine("Running some other code...");
actionRunner.RunAction();
其他提示
我们的想法是,你处理的catch块例外...
这就是说,例外是引用类型,所以可以始终声明在try范围之外的异常可变...
Exception dontDoThis;
try
{
foo.DoSomething();
}
catch(Exception e)
{
dontDoThis = e;
}
finally
{
// use dontDoThis...
}
如果你正在寻找捕捉你应该处理的 UnhandledException 。您应该只在您打算处理(而不仅仅是登录)下级捕获异常,否则你应该让他们泡起来,在更高层次上被捕获,或者我在UnhandledException方法之前提到的。
不隶属于 StackOverflow