locked
Try in a Finally Block RRS feed

  • Question

  • I have a general question about try-catch-finally and what is allowed in C# and the Compact Framework 2.0.  This is a question both from the perspective of what is allowed in the Language, what the compiler allows (if not allowed in the language) and what works / doesn't work.

    Lets look at this code:

    try
    {
      // Some Code that throws
    }
    catch (System.Exception e)
    {
      // Handle Exception, but don't re-throw
    }
    finally
    {
      try
      {
        // Do some Deinit that can throw
      }
      catch (System.Exception e)
      {
        // Handle Exception or re-throw
      }
    }

    My question is basically, is there a problem with having a try-catch or try-finally or try-catch-finally block within a finally block?

    I understand that having an exception thrown from a finally block basically overwrites, or causes a previous exception (that is moving up the stack) to be lost.  But other than that is this legal?  Are there any other shortcomings, pitfalls or problems?

    Thank you,

    Brad.

    Wednesday, November 3, 2010 12:01 AM

Answers

  • Hi,

    Yes, this is right. Generally, we don't code like this, we release some resource in the finally statement, which don't cause exception. If you are not sure whether it will cause an exception in fincally statement, you can add a try in it.

     

    Best regards,
    Guang-Ming Bian - MSFT


    Please remember to mark the replies as answers if they help and unmark them if they provide no help
    Friday, November 5, 2010 9:56 AM