locked
difference between finally and finalize block inexception handling?? RRS feed

  • Question

  • difference between finally and finalize block inexception handling??Explain with example.
    Friday, February 8, 2019 5:14 AM

All replies

  • They are different things and finalizers are not a part of exception handling.

    Finally is the block that is executed on exception handling if or not exception occurred. So it gives you change to do operations or cleanup after everything else in try-catch-finally-block. So it is for method level clean up.

    Finalizer is deconstructor to do any cleanup when garbage collector collects instance of the class. Finalizer is for instance level clean up.

    Friday, February 8, 2019 9:56 AM
  • Hi Anas Babar

    Thank you for posting here.

    For your question, you want to know the difference between finally and finalize block in exception handling.

    Finally: The code inside a final block will get executed regardless of whether or not there is an exception.

    Code example:

    static void Main(string[] args)
    
            {
    
                try
    
                {
    
                    string path = @"c:/1.txt";
    
                    string m = File.ReadAllText(path);
    
                }
    
                catch(Exception e)
    
                {
    
                    Console.WriteLine(e.ToString());
    
                }
    
                finally
    
                {
    
                    Console.WriteLine("hello");
    
                }
    
                Console.ReadKey();
    
            }


    Finalize: It is used to release the unmanaged resource. If we call the destructor, it will call the finalize method automatically.

    Code example:

    Please see the following code.

    https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/destructors

    Hope my explanation could be helpful.

    Best regards,

    Jack


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.


    Monday, February 11, 2019 8:26 AM