简体   繁体   中英

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:

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? Because if there is already an exception raised then there's nothing to 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

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

// ...

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 ). The finally block may trigger it's own exception, which is what the inner catch will catch.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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