简体   繁体   English

这种设计模式实现了什么?

[英]What does this design pattern accomplish?

I'm trying to figure out what this code sample in my book accomplishes. 我试图弄清楚我的书中的代码示例是什么。 It says 它说

Add an inner try-catch block in the finally block of the outer exception handler to prevent losing exception information: 在外部异常处理程序的finally块中添加内部try-catch块,以防止丢失异常信息:

private void PreventLossOfExeptionFormat()
{
   try
   {
       // ... 
   }
   catch(Exception e)
   {
       Console.WriteLine("Error message == " + e.Message);
       throw;
   }
   finally
   {
       try
       { 
          // ...
       }
       catch(Exception e)
       {
           Console.WriteLine("An unexpected error occured in the finally block. Error message: " + e.Message);
       }
   }
}

How is the outer exception getting into the inner one? 外部异常如何进入内部异常? I understand that in the outer catch block it's getting thrown into the finally block, but does it then get immediately caught in the catch of the finally block or what is the point of the try inside there? 我理解在外部catch块中它被抛入finally块,但它是否会立即catchfinally块的catch或者内部try的重点是什么? Because if there is already an exception raised then there's nothing to try ... 因为如果已经有异常,那么就没有什么可以try ......

How is the outer exception getting into the inner one? 外部异常如何进入内部异常?

It is not. 它不是。

I understand that in the outer catch block it's getting thrown into the finally block 据我所知,在外部catch块中它被抛入finally块

Yes. 是。

Because if there is already an exception raised then there's nothing to try 因为如果已经提出异常,那么就没有什么可试的了

You seem to ignore what is obvious to read. 你好像忽略了什么是明显的阅读。 The inner try catch in the outer finally is there to catch an exception in the lines that you marked as 外部的try try catch最终用于捕获您标记为的行中的异常

// ... // ...

Ie finally is suppose to do something that MAY THROW IT'S OWN EXCEPTION. 也就是说,最后我想做的事情可能是他自己的例外。

Remember that the finally block is always called, whether you have an outer exception or not (it's not triggered by the outer throw ). 请记住,无论你是否有外部异常(它都不是由外部throw触发),总是会调用finally块。 The finally block may trigger it's own exception, which is what the inner catch will catch. finally块可能会触发它自己的异常,这就是内部catch会捕获的异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM