[英]C# Exception Handling - will last catch block fetch re-thrown Exception?
I'm wondering if this code will work in the way that after 10 retries CleanUp()
will be called?我想知道这段代码是否可以在 10 次重试后调用CleanUp()
的方式工作? Or will the throw new Exception()
not get caught by the last catch block?或者throw new Exception()
不会被最后一个 catch 块捕获?
public void Process()
{
try
{}
catch (MyException e)
{
int retries = GetRetries();
if(retries > 10)
{
_logger.LogError("Retried event already {retries} times. Giving up.", retries);
throw new Exception("Giving up!");
}
Process();
}
catch (Exception e)
{
CleanUp();
}
}
No, it doesn't work like that.不,它不是那样工作的。 For any given try
/ catch
block, only an exception originating in the try
can be caught by the corresponding catch
blocks.对于任何给定的try
/ catch
块,只有源于try
的异常才能被相应的catch
块catch
。 Exceptions thrown within catch
blocks are not catchable by other catch
blocks at the same level.在catch
块中抛出的异常不能被同一级别的其他catch
块catch
。
finally
blocks allow you to run code when control leaves a try
/ catch
for any reason. finally
块允许您在控件因任何原因离开try
/ catch
时运行代码。 So if the end of your try
already has a CleanUp
then you would just change your final catch(Exception e)
to finally
and remove the CleanUp
at the end of the try
part.因此,如果您的try
结束时已经有了CleanUp
那么您只需将最终catch(Exception e)
更改为finally
并在try
部分的末尾删除CleanUp
。
If, however, you only want to run CleanUp
when control leaves the try
/ catch
via an exception , you're not so lucky.但是,如果您只想在控制通过异常离开try
/ catch
时运行CleanUp
,那么您就没有那么幸运了。 There is a fault
clause in IL, which is finally
, but only for exceptions, but that's not exposed in C#. IL 中有一个fault
子句,它是finally
,但仅用于异常,但在 C# 中没有公开。
So if you need that, it's usually best to introduce an extra bool
that indicates you reached the end of the try
block without exception, and use that to make your CleanUp
call conditional in the finally
.因此,如果您需bool
,通常最好引入一个额外的bool
指示您无一例外地到达了try
块的末尾,并使用它使您的CleanUp
调用在finally
有条件。
Or you may simulate try
/ catch
/ fault
by nesting try
/ catch
blocks:或者你可以通过嵌套try
/ catch
块来模拟try
/ catch
/ fault
:
try
{
try
{}
catch (MyException e)
{
int retries = GetRetries();
if(retries > 10)
{
_logger.LogError("Retried event already {retries} times. Giving up.", retries);
throw new Exception("Giving up!");
}
Process();
}
}
catch
{
//Act as fault
CleanUp();
throw;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.