Exception Handling Statements (C# Reference)

Exception Handling Statements (C# Reference)

C# provides built-in support for handling anomalous situations, known as exceptions, which may occur during the execution of your program. These exceptions are handled by code that is outside the normal flow of control.

The following exception handling topics are explained in this section:

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.

For more information about the finallyblock, see try-finally.

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

        finally
        {
            if (file != null)
            {
                file.Close();
            }
        }
        // Do something with buffer...
    }

}
原文地址:https://www.cnblogs.com/chucklu/p/4653713.html