Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All
Important This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here.

try-catch-finally (C# Reference)

A common usage of catch and finally together is to obtain and use resources in a try block, deal with exceptional circumstances in a catch block, and release the resources in the finally block.

For more information and examples on re-throwing exceptions, see try-catch and Throwing Exceptions.

public class EHClass
    void ReadFile(int index)
        // To run this code, substitute a valid path from your local machine 
        string path = @"c:\users\public\test.txt";
        System.IO.StreamReader file = new System.IO.StreamReader(path);
        char[] buffer = new char[10];
            file.ReadBlock(buffer, index, buffer.Length);
        catch (System.IO.IOException e)
            Console.WriteLine("Error reading from {0}. Message = {1}", path, e.Message);

            if (file != null)
        // Do something with buffer...


For more information, see the following sections in the C# Language Specification:

  • Try-catch-finally statements

  • 8.10 The try statement

  • 16 Exceptions

Community Additions

© 2015 Microsoft