Skip to main content

C++ Exception handling


#include <stdexcept>

Exception

  • class logic_error; - 논리적 사전 조건 위반과 같이 프로그램이 실행되기 전에 검색될 수 있는 오류를 보고하기 위해 발생하는 모든 예외
    • class domain_error; - 도메인 오류를 보고하기 위해 발생하는 모든 예외
    • class invalid_argument; - 잘못된 인수를 보고하기 위해 발생하는 모든 예외
    • class length_error; - 너무 길어서 지정할 수 없는 개체 생성 시도를 보고하기 위해 발생하는 모든 예외
    • class out_of_range; - 유효 범위를 벗어난 인수를 보고하기 위해 발생하는 모든 예외
  • class runtime_error; - 프로그램이 실행되는 경우에만 검색될 수 있는 오류를 보고하기 위해 발생하는 모든 예외
    • class range_error; - 범위 오류를 보고하기 위해 발생하는 모든 예외
    • class overflow_error; - 산술 오버플로를 보고하기 위해 발생하는 모든 예외
    • class underflow_error; - 산술 언더플로를 보고하기 위해 발생하는 모든 예외
class logic_error : public exception {
public:
explicit logic_error(const string& what_arg);
explicit logic_error(const char* what_arg);
};

class runtime_error : public exception {
public:
explicit runtime_error(const string& what_arg);
explicit runtime_error(const char* what_arg);
};

Exception specification

void func( void ) noexcept;
void func( void ) noexcept( true );
void func( void ) throw();

위 선언 모두 해당 함수는 예외를 throw 하지 않는다는 선언입니다. noexcept를 권장합니다.

Custom exception

class custom_error : public std::exception
{
private:
const char *m_what_arg;

public:
explicit custom_error( const std::string &what_arg )
: m_what_arg( what_arg.c_str() )
{
}
explicit custom_error( const char *what_arg )
: m_what_arg( what_arg )
{
}
virtual const char *what() const throw()
{
return m_what_arg;
}
};

try, catch

try
{
...
}
catch( const std::exception &e )
{
std::cerr << e.what() << std::endl;
...
}
caution

ld를 사용하는 경우 shared library에서 발생하는 예외는 catch하지 못할 수 있습니다. g++을 사용하거나 static library를 사용하시기 바랍니다.