C++ Chapter 14.4 : std::exception
카테고리: Cpp
태그: Cpp Programming
인프런에 있는 홍정모 교수님의 홍정모의 따라 하며 배우는 C++ 강의를 듣고 정리한 필기입니다. 😀  
🌜 [홍정모의 따라 하며 배우는 C++]강의 들으러 가기!
chapter 14. 예외처리 : std::exception
🔔 std::exception
#include <exception>
if-else문을 통해 예외를 인지하게 한 후 직접throw를 던졌었지만 문제가 생기면 std::exception 클래스를 통해 시스템 상 내부에서 알아서 발생한 예외를 throw 한다.- C++ 표준 클래스로, 예외의 여러 종류들을 나타내는 여러 자식 클래스들을 두고 있다.
    
- runtime_error 클래스, logic_error 클래스 등등 C++ 표준의 exception 클래스 를 상속받고 있다.
 
 
#include <iostream>
#include <string>
#include <exception>
int main()
{
   try
   {
       std::string s;
       s.resize(-1);  // 예외 발생
   }
   catch (std::exception & e)
   {
       std::cout << typeid(e).name() << std::endl;
       std::cerr << e.what() << std::endl;
   }
   
   return 0;
}
💎출력💎
class std::length_error
string too long 
string 문자열의 사이즈를 -1로 지정해서 문제가 발생
throw없이도 시스템상 내부에서 알아서 예외 종류에 알맞는 std::exception 클래스의 자식 클래스를 던져 준다.- 길이에 대한 에러이므로 std::exception 클래스의 자식 클래스 중 하나인 std::length_error 예외 클래스 객체가 던져진다.
        
throw std::length_error(s)이 숨겨져 있는 것이나 마찬가지.
 catch (std::exception & e)에서 이를 받는다.
- 길이에 대한 에러이므로 std::exception 클래스의 자식 클래스 중 하나인 std::length_error 예외 클래스 객체가 던져진다.
        
 typeid(e).name()- “class std::length_error” 출력
 
what 함수
예외 종류에 맞는 에러 원인 메세지를 리턴하는 기능을 하는 함수다.
- 에러 메세지를 리턴하므로 리턴 타입은 
const char *이다. 
std::exception 클래스의 모든 자식 클래스는 virtual 가상 함수인 what() 함수를 오버라이딩 한다.
e.what()- “string too long” 출력
        
- std::length_error 클래스에서는 what() 함수를 “string too long” 출력 하도록 오버라이딩 해놨기 때문에 이렇게 나온 것!
 
 
- “string too long” 출력
        
 
🔔 std::exception 상속 받는 사용자 정의 클래스 만들기
: public std::exception해주어 상속 받고 what 함수를 아래와 같이 오버라이딩 해주어야 한다.
#include <iostream>
#include <string>
#include <exception>
class CustomException : public std::exception
{
public:
    const char * what() const noexcept override
    {
        return "Custom exception";
    }
};
int main()
{
   try
   {
       throw CustomException();  // 예외 발생
   }
   catch (std::exception & e)
   {
       std::cout << typeid(e).name() << std::endl;
       std::cerr << e.what() << std::endl;
   }
   
   return 0;
}
💎출력💎
class CustomException
Custom exception
const char * what() const noexcept overrideconst타입의 객체만 호출할 수 있으며noexcept- 이 안에선 예외를 던지지 않겠다는 의미. C++ 11 이상부터 사용 가능.
 
🌜 개인 공부 기록용 블로그입니다. 오류나 틀린 부분이 있을 경우 
언제든지 댓글 혹은 메일로 지적해주시면 감사하겠습니다! 😄
      
    
댓글 남기기