다음을 통해 공유


try-finally(C# 참조)

finally 블록에 할당 되는 리소스 정리에 대 한 유용 합니다는 시도 차단 하 고 임의의 코드 실행을 해야 실행에서 예외가 발생 하는 경우에는 try 블록입니다.문을 일반적으로 finally 블록 실행 시는 try 문을 전송 컨트롤의 정상적인 실행의 실행으로 인해 발생 하는지는 break, continue, goto, 또는 return 문 또는 예외를 전파는 try 문.

처리 된 예외에 연결 된 내 finally 블록 실행 되도록 보장 됩니다.그러나 예외는 처리 되지 않은 경우 실행 하는 finally 블록에 종속 됩니다 예외 해제 방법을 작업 시작 됩니다.차례로, 컴퓨터 설정 방법에 따라 달라 집니다.자세한 내용은 CLR에서 처리 되지 않은 예외 처리.

일반적으로 때 처리 되지 않은 예외가 끝나는 응용 프로그램 인지 여부는 finally 블록 실행 중요 하지 않습니다.그러나 문이 경우는 finally 이 경우에 경우에 하나의 솔루션을 실행 해야 하는 차단 되어 추가할 수는 catch 차단 하는 try-finally 문입니다.또는 throw 될 수 있습니다에 예외를 catch 할 수 있는 try 의 차단는 try-finally 문에 호출 스택의 상위.메서드를 포함 하는 메서드를 예외를 catch 할 수 있습니다, 해당 try-finally 문을 호출 스택에 있는 메서드 또는 해당 메서드를 호출 하는 방법에서.예외가 catch 되지 않는 경우 실행 하는 finally 블록 따라 운영 시스템 예외를 트리거할 선택 여부에 작업을 해제 합니다.

예제

다음 예제에서는 잘못 된 변환 문이 발생 한 System.InvalidCastException 예외입니다.예외 처리 되지 않습니다.

public class ThrowTestA
{
    static void Main()
    {
        int i = 123;
        string s = "Some string";
        object obj = s;

        try
        {
            // Invalid conversion; obj contains a string, not a numeric type.
            i = (int)obj;

            // The following statement is not run.
            Console.WriteLine("WriteLine at the end of the try block.");
        }
        finally
        {
            // To run the program in Visual Studio, type CTRL+F5. Then 
            // click Cancel in the error dialog.
            Console.WriteLine("\nExecution of the finally block after an unhandled\n" +
                "error depends on how the exception unwind operation is triggered.");
            Console.WriteLine("i = {0}", i);
        }
    }
    // Output:
    // Unhandled Exception: System.InvalidCastException: Specified cast is not valid.
    //
    // Execution of the finally block after an unhandled
    // error depends on how the exception unwind operation is triggered.
    // i = 123
}

다음 예제에서 예외는 TryCast 메서드 메서드 호출 스택 위로 더 멀리에서 발견입니다.

public class ThrowTestB
{
    static void Main()
    {
        try
        {
            // TryCast produces an unhandled exception.
            TryCast();
        }
        catch (Exception ex)
        {
            // Catch the exception that is unhandled in TryCast.
            Console.WriteLine
                ("Catching the {0} exception triggers the finally block.",
                ex.GetType());

            // Restore the original unhandled exception. You might not
            // know what exception to expect, or how to handle it, so pass 
            // it on.
            throw;
        }
    }

    public static void TryCast()
    {
        int i = 123;
        string s = "Some string";
        object obj = s;

        try
        {
            // Invalid conversion; obj contains a string, not a numeric type.
            i = (int)obj;

            // The following statement is not run.
            Console.WriteLine("WriteLine at the end of the try block.");
        }
        finally
        {
            // Report that the finally block is run, and show that the value of
            // i has not been changed.
            Console.WriteLine("\nIn the finally block in TryCast, i = {0}.\n", i);
        }
    }
    // Output:
    // In the finally block in TryCast, i = 123.

    // Catching the System.InvalidCastException exception triggers the finally block.

    // Unhandled Exception: System.InvalidCastException: Specified cast is not valid.
}

에 대 한 자세한 내용은 finally를 참조 하십시오 try-catch-마지막.

C#도 포함는 문을 사용 하 여와 같은 기능에 대 한 편리한 구문을 제공은 try-finally 문.

C# 언어 사양

자세한 내용은 C# 언어 사양을 참조하십시오. 이 언어 사양은 C# 구문 및 사용법에 대한 신뢰할 수 있는 소스입니다.

참고 항목

작업

방법: 명시적으로 예외 Throw

참조

C# 키워드

try, catch 및 throw 문을 (c, + +)

예외 처리문(C# 참조)

throw(C# 참조)

try-catch(C# 참조)

개념

C# 프로그래밍 가이드

기타 리소스

C# 참조