Visual C++에서 예외 catch

이 문서에서는 블록을 사용하여 예외를 try-catch-finally catch하는 방법을 설명합니다.

원래 제품 버전: Visual C++
원래 KB 번호: 815662

요약

try-catch-finally 블록은 예외가 발생할 수 있는 모든 코드 주위에 배치하는 래퍼입니다. 예외를 catch하고 처리하는 것은 표준 프로그래밍 작업입니다.

try-catch-finally 블록은 다음 섹션으로 구성됩니다.

  • 예외를 throw할 수 있는 모든 코드는 try 블록 내에 배치됩니다.
  • 예외가 throw되면 블록이 catch 입력되고 프로그램이 적절한 작업을 수행하여 복구하거나 사용자에게 경고할 수 있습니다.
  • 블록의 finally 코드는 항상 실행되며 예외가 발생한 후 클린 수행할 수 있습니다. 블록은 finally 선택 사항입니다.

이 문서에서는 Microsoft .NET Framework 클래스 라이브러리 네임스페이스 및 System.Security를 참조합니다System.IO.

Visual C++ .NET에서 예외 catch

  1. Visual Studio .NET을 시작합니다.

  2. 파일 메뉴에서 새로 만들기를 가리킨 다음 프로젝트를 클릭합니다.

  3. Visual C++의 프로젝트 형식에서 Visual C++를 클릭한 다음 템플릿 아래의 CLR 콘솔 애플리케이션 클릭합니다.

  4. 이름 상자에 Q815662 입력한 다음 확인을 클릭합니다.

  5. Q815662.cpp 코드 창의 모든 코드를 다음 코드로 바꿉 있습니다. 이 코드는 세 개의 변수를 선언하고 초기화합니다. k를 초기화하면 오류가 발생합니다.

    #include "stdafx.h"
    #using <mscorlib.dll>
    #include <tchar.h>
    using namespace System;
    void _tmain(void)
    {
        Console::WriteLine("We're going to divide 10 by 0 and see what happens...");
        Console::WriteLine();
        int i = 10;
        int j = 0;
        int k = i/j; //Error on this line.
    }
    
  6. F5. 예외가 발생합니다 System.DivideByZeroException .

  7. try-catch 코드를 중심으로 문을 래핑하여 오류를 캡처합니다. 다음 코드는 코드에서 throw된 모든 오류를 catch하고 일반 오류 메시지를 표시합니다. Q815662.cpp 코드 창의 코드를 다음 코드로 바꿉 있습니다.

    #include "stdafx.h"
    #using <mscorlib.dll>
    #include <tchar.h>
    using namespace System;
    void _tmain(void)
    {
        try
        {
            Console::WriteLine("We're going to divide 10 by 0 and see what happens...");
            Console::WriteLine();
            int i = 10;
            int j = 0;
            int k = i/j; //Error on this line.
        }
        catch(...)
        {
            Console::WriteLine("An error occurred.");
        }
    }
    
  8. Ctrl+F5를 눌러 애플리케이션을 실행합니다.

    참고

    시스템 예외 오류 메시지 catch 대신 블록의 오류 메시지가 표시됩니다.

  9. 오류에 관계없이 클린 또는 사후 처리를 수행해야 하는 경우 문의 일부를 try-catch-finally 사용합니다__finally. 문의 마지막 부분에 있는 코드는 예외에 관계없이 항상 실행됩니다. 다음 코드는 오류가 발생하지 않은 경우에도 콘솔에 다음 메시지를 표시합니다.

    This statement is always printed.  
    

    Q815662.cpp 코드 창의 코드를 다음 코드로 바꿉 있습니다.

    #include "stdafx.h"
    #using <mscorlib.dll>
    #include <tchar.h>
    using namespace System;
    void _tmain(void)
    {
        try
        {
            Console::WriteLine("We're going to divide 10 by 0 and see what happens...");
            Console::WriteLine();
            int i = 10;
            int j = 0;
            int k = i/j; //Error on this line.
        }
        catch(...)
        {
            Console::WriteLine("An error occurred.");
        }
        __finally //This section is performed regardless of the above processing.
        {
            Console::WriteLine();
            Console::WriteLine("This statement is always printed");
        }
    }
    
  10. Ctrl+F5를 눌러 프로젝트를 실행합니다.

  11. catch 문과 함께 예외 개체를 사용하여 예외에 대한 세부 정보를 검색할 수 있습니다. 예외 개체에는 원본을 식별하는 데 도움이 되는 여러 속성이 있으며 예외에 대한 스택 정보가 있습니다. 이 정보는 예외의 원래 원인을 추적하는 데 유용하거나 원본에 대한 더 나은 설명을 제공할 수 있습니다. 다음 샘플에서는 예외를 catch하고 특정 오류 메시지를 제공합니다. Q815662.cpp 코드 창의 코드를 다음 코드로 바꿉 있습니다.

    #include "stdafx.h"
    #using <mscorlib.dll>
    #include <tchar.h>
    using namespace System;
    using namespace System::Reflection;
    void _tmain(void)
    {
        try
        {
            Console::WriteLine("We're going to divide 10 by 0 and see what happens...");
            Console::WriteLine();
            int i = 10;
            int j = 0;
            int k = i/j; //Error on this line.
        }
        catch(Exception *e)
        {
            Console::WriteLine("An error occurred.");
            Console::WriteLine(e->Message); // Print the error message.
            Console::WriteLine(e->StackTrace); //String that contains the stack trace for this exception.
        }
        __finally //This section is performed regardless of the above processing.
        {
            Console::WriteLine();
            Console::WriteLine("This statement is always printed");
        }
        Console::ReadLine();
    }
    
  12. 이 시점까지는 특정이 아닌 예외를 처리했습니다. 그러나 어떤 종류의 예외가 발생할지 미리 알고 있는 경우 예상되는 예외를 catch하고 그에 따라 처리할 수 있습니다. 다음 코드에 설명된 여러 catch 블록을 사용하여 다른 모든 예외를 catch하고 처리합니다.

    #include "stdafx.h"
    #using <mscorlib.dll>
    #include <tchar.h>
    using namespace System;
    using namespace System::IO;
    using namespace System::Security;
    void _tmain(void)
    {
        try
        {
            File::Create("c:\\temp\\testapp.txt"); //Can fail for a number of resons
        }
        // This error may occur if the temp folder does not exist.
        catch(IOException *ioe)
        {
            Console::WriteLine("An IOException exception occurred!");
            Console::WriteLine(ioe->ToString());
        }
        // You do not have the appropriate permission to take this action.
        catch(SecurityException *se)
        {
            Console::WriteLine("An SecurityException exception occur")
        }
        // Catch all exceptions
        catch(Exception *e)
        {
            Console::WriteLine(e->ToString());
        }
    }
    

    컴퓨터 구성이 다를 수 있으므로 이 단계의 샘플은 예외를 throw하거나 throw하지 않을 수 있습니다. IO(입력/출력) 예외를 강제로 적용하려면 파일 경로를 컴퓨터에 없는 폴더로 변경합니다.