checked(C# 참조)

checked 키워드는 정수 계열 형식의 산술 연산 및 변환에 대한 오버플로 검사를 명시적으로 활성화하는 데 사용됩니다.

기본적으로 식이 대상 형식의 범위를 벗어난 값을 생성하는 경우 상수 값만 포함된 식에서 컴파일러 오류가 발생합니다. 식이 상수가 아닌 값을 하나 이상 포함하는 경우 컴파일러에서 오버플로를 검색하지 않습니다. 다음 예제에서는 i2에 할당된 식을 평가해도 컴파일러 오류가 발생하지 않습니다.

// The following example causes compiler error CS0220 because 2147483647
// is the maximum value for integers. 
//int i1 = 2147483647 + 10;

// The following example, which includes variable ten, does not cause
// a compiler error.
int ten = 10;
int i2 = 2147483647 + ten;

// By default, the overflow in the previous statement also does
// not cause a run-time exception. The following line displays 
// -2,147,483,639 as the sum of 2,147,483,647 and 10.
Console.WriteLine(i2);

기본적으로 상수가 아닌 이러한 식에서는 런타임에 오버플로가 확인되지 않으며, 오버플로 예외가 발생하지 않습니다. 이전 예제에서는 두 양의 정수의 합계로 -2,147,483,639를 표시합니다.

컴파일러 옵션, 환경 구성 또는 checked 키워드 사용을 통해 오버플로 검사를 활성화할 수 있습니다. 다음 예제에서는 checked 식이나 checked 블록을 사용하여 런타임에 이전 합계에 의해 생성된 오버플로를 검색하는 방법을 보여 줍니다. 두 예제에서 모두 오버플로 예외가 발생합니다.

// If the previous sum is attempted in a checked environment, an 
// OverflowException error is raised.

// Checked expression.
Console.WriteLine(checked(2147483647 + ten));

// Checked block.
checked
{
    int i3 = 2147483647 + ten;
    Console.WriteLine(i3);
}

unchecked 키워드를 사용하여 오버플로 검사를 차단할 수 있습니다.

예제

이 샘플에서는 checked를 사용하여 런타임에 오버플로 검사를 활성화하는 방법을 보여 줍니다.

class OverFlowTest
{
    // Set maxIntValue to the maximum value for integers.
    static int maxIntValue = 2147483647;

    // Using a checked expression.
    static int CheckedMethod()
    {
        int z = 0;
        try
        {
            // The following line raises an exception because it is checked.
            z = checked(maxIntValue + 10);
        }
        catch (System.OverflowException e)
        {
            // The following line displays information about the error.
            Console.WriteLine("CHECKED and CAUGHT:  " + e.ToString());
        }
        // The value of z is still 0.
        return z;
    }

    // Using an unchecked expression.
    static int UncheckedMethod()
    {
        int z = 0;
        try
        {
            // The following calculation is unchecked and will not 
            // raise an exception.
            z = maxIntValue + 10;
        }
        catch (System.OverflowException e)
        {
            // The following line will not be executed.
            Console.WriteLine("UNCHECKED and CAUGHT:  " + e.ToString());
        }
        // Because of the undetected overflow, the sum of 2147483647 + 10 is 
        // returned as -2147483639.
        return z;
    }

    static void Main()
    {
        Console.WriteLine("\nCHECKED output value is: {0}",
                          CheckedMethod());
        Console.WriteLine("UNCHECKED output value is: {0}",
                          UncheckedMethod());
    }
    /*
   Output:
   CHECKED and CAUGHT:  System.OverflowException: Arithmetic operation resulted
   in an overflow.
      at ConsoleApplication1.OverFlowTest.CheckedMethod() 

   CHECKED output value is: 0
   UNCHECKED output value is: -2147483639
 */
}

C# 언어 사양

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

참고 항목

참조

C# 키워드

Checked 및 Unchecked(C# 참조)

unchecked(C# 참조)

개념

C# 프로그래밍 가이드

기타 리소스

C# 참조