다음을 통해 공유


try-finally(C# 참조)

finally 블록을 사용하여 try 블록에 할당된 리소스를 정리하고 try 블록에 예외가 발생하더라도 코드를 실행할 수 있습니다. 일반적으로 컨트롤이 try 문을 나갈 때 finally 블록 문이 실행됩니다. 컨트롤 전송은 일반 실행, break, continue, goto 또는 return 문 실행 또는 try 문에서 예외 전파의 결과로 발생할 수 있습니다.

처리된 예외 안에서는 연결된 finally 블록이 반드시 실행됩니다. 그러나 예외가 처리되지 않은 경우 finally 블록은 예외 해제 작업이 트리거되는 방법에 따라 다르게 실행됩니다. 이것도 컴퓨터 설정 방법에 따라 다릅니다. 자세한 내용은 Unhandled Exception Processing in the CLR을 참조하십시오.

일반적으로 처리되지 않은 예외로 응용 프로그램이 종료되면 finally 블록의 실행 여부는 중요하지 않습니다. 그러나 이러한 상황에서도 실행되어야 하는 finally 블록의 문이 있는 경우 하나의 솔루션은 catch 블록을 try-finally 문에 추가하는 것입니다. 또는 높은 호출 스택에 있는 try-finally의 try 블록에서 throw될 수 있는 예외를 catch할 수 있습니다. try-finally 문이 포함된 메서드를 호출하는 메서드에서, 이 메서드를 호출하는 메서드에서 또는 호출 스택의 모든 메서드에서 예외를 catch할 수 있습니다. 예외가 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 메서드 예외는 메서드에서 호출 스택까지 catch됩니다.

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-finally를 참조하십시오.

C#에는 using 문도 포함됩니다. 이 문은 간편한 구문에서 IDisposable 개체에 대해 비슷한 기능을 제공합니다.

C# 언어 사양

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

참고 항목

작업

방법: 명시적으로 예외 Throw

참조

C# 키워드

Try, Throw 및 Catch 문(C++)

예외 처리문(C# 참조)

throw(C# 참조)

try-catch(C# 참조)

개념

C# 프로그래밍 가이드

기타 리소스

C# 참조