try-catch-finally(C# 참조)

업데이트: 2007년 11월

일반적으로 catch와 finally를 함께 사용하여 try 블록에서 리소스를 가져와 사용하고 catch 블록에서 예외 상황을 처리한 다음, finally 블록에서 리소스를 해제합니다.

예외를 다시 throw하는 것에 대한 자세한 내용 및 예제는 try-catch예외 throw를 참조하십시오.

예제

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];
        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...
    }

}

C# 언어 사양

자세한 내용은 C# 언어 사양의 다음 단원을 참조하십시오.

  • 5.3.3.15 Try-catch-finally 문

  • 8.10 try 문

  • 16 예외

참고 항목

작업

방법: 명시적으로 예외 Throw

개념

C# 프로그래밍 가이드

참조

C# 키워드

The try, catch, and throw Statements

예외 처리문(C# 참조)

throw(C# 참조)

using 문(C# 참조)

기타 리소스

C# 참조