반응형

예외(Exception) 기본

  • throw, try, catch
  • throw를 사용해서 예외를 던짐
  • throw된 예외는 반드시 잡아서 처리해야 하며, 처리하지 않은 경우 abort() 함수를 수행하고 종료됨
  • try ~catch 구문을 사용해서 예외 처리

Catch(...)

  • 모든 종류의 예외를 잡을 수 있음
  • catch를 여러개 만들때는 반드시 마지막에 놓아야 함
#include <iostream>

int foo()
{
    if (1) // 예외조건 가정
        throw 1;

    return 0;
}

int main()
{
    try
    {
        foo();
    }
    catch (int n)
    {
        std::cout << "예외 발생" << std::endl;
    }
    catch (...)
    {
        std::cout << "... 예외 발생" << std::endl;
    }
    std::cout << "계속실행" << std::endl;
}

std::exception

  • C++ 표준 예외의 최상위 클래스
  • what() 가상함수 제공
#include <iostream>

class MemoryException : public std::exception // 예외 클래스 정의, std::exception 상속
{
public:
    virtual const char* what() const noexcept // std::exception의 가상함수 what() 구현
    {
        return "메모리 예외";
    }
};

int foo()
{
    if (1) // 예외조건 가정
        throw MemoryException(); // 사용자 정의 예외 클래스 throw

    return 0;
}

int main()
{
    try
    {
        foo();
    }
    catch (MemoryException & e)
    {
        std::cout << e.what() << std::endl;
    }

    std::cout << "계속실행" << std::endl;
}

C++ 표준 예외 클래스

  • std::bad_alloc
  • std::range_error
  • std::out_of_range
#include <iostream>

int main()
{
    try
    {
        int* p = new int[100]; // C++ 메모리 할당 실패시 예외 발생
    }
    catch (std::bad_alloc & e)
    {
        std::cout << e.what() << std::endl;
    }
}

noexcept

  • 함수에 예외가 없음을 명시적으로 표기하는 방법
  • throw() 동일 역할
  • 명시 할경우 컴파일러 최적화시에 도움됨
  • noexcept() 함수로 예외 없음 여부를 조사 할 수 있음
#include <iostream>

// 예외가 없는 함수
void a() noexcept {}
void a1() throw() {}

int main()
{
    bool ba = noexcept( a() ); //예외 없음 여부 조사 가능
    bool ba1 = noexcept( a1() );
    std::cout << ba << "," << ba1 << std::endl;
}
반응형

+ Recent posts