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๋ฅผ ์‚ฌ์šฉํ•˜์‹œ๊ธฐ ๋ฐ”๋ž๋‹ˆ๋‹ค.

Last updated on