C++ 예외 클래스와 상속 (Exception Class and Inheritance)

2021. 3. 22. 00:10·SW개발/C++
목차
  1. 예외 클래스
  2. 예외 클래스를 상속해서 사용하기
  3. rethrow
반응형

예외 클래스와 상속 (Exception Class and Inheritance)

예외 클래스

  • 예외 상황을 처리할 때 필요한 변수나 함수를 멤버로 가진 클래스

  • 예외 클래스를 사용하지 않은 예제

    #include <iostream>
    
    using namespace std;
    
    class MyArray
    {
      int        data_[5];
    
    public:
      int& operator[] (const int& index)
      {
        if (index < 0 || index >= 5)
          throw -1;
        return data_[index];
      }
    };
    
    void        doSomething()
    {
      MyArray    my_array;
    
      try
      {
        my_array[100];
      }
      catch (const int& x)
      {
        cerr << "Exception " << x << endl;
      }
    }
    
    int            main()
    {
      doSomething();
    }
    
    /* stdout stderr
    Exception -1
    */

  • 예외 클래스를 직접 만들어서 사용하기

    #include <iostream>
    
    using namespace std;
    
    class Exception
    {
    public:
      void    report()
      {
        cerr << "Exception report\n";
      }
    };
    
    class MyArray
    {
      int        data_[5];
    
    public:
      int& operator[] (const int& index)
      {
        if (index < 0 || index >= 5)
          throw Exception();
        return data_[index];
      }
    };
    
    void        doSomething()
    {
      MyArray    my_array;
    
      try
      {
        my_array[100];
      }
      catch (Exception& e)
      {
        e.report();
      }
    }
    
    int            main()
    {
      doSomething();
    }
    
    /* stdout stderr
    Exception report
    */

예외 클래스를 상속해서 사용하기

  • 다형성을 적용하지 않는 경우

    #include <iostream>
    
    using namespace std;
    
    class Exception
    {
    public:
      void    report()
      {
        cerr << "Exception report\n";
      }
    };
    
    class ArrayException : public Exception
    {
    public:
      void    report()
      {
        cerr << "Array exception report\n";
      }
    };
    
    class MyArray
    {
      int        data_[5];
    
    public:
      int& operator[] (const int& index)
      {
        if (index < 0 || index >= 5)
          throw ArrayException();
        return data_[index];
      }
    };
    
    void        doSomething()
    {
      MyArray    my_array;
    
      try
      {
        my_array[100];
      }
      catch (Exception& e)
      {
        e.report();
      }
    }
    
    int            main()
    {
      doSomething();
    }
    
    /* stdout stderr
    Exception report
    */
    • 객체 잘림으로 인해 Exception::report() 함수가 작동한 것을 알 수 있다.
  • 다형성을 적용한 경우 (virtual 키워드 사용)

    #include <iostream>
    
    using namespace std;
    
    class Exception
    {
    public:
      virtual void    report()
      {
        cerr << "Exception report\n";
      }
    };
    
    class ArrayException : public Exception
    {
    public:
      void    report()
      {
        cerr << "Array exception report\n";
      }
    };
    
    class MyArray
    {
      int        data_[5];
    
    public:
      int& operator[] (const int& index)
      {
        if (index < 0 || index >= 5)
          throw ArrayException();
        return data_[index];
      }
    };
    
    void        doSomething()
    {
      MyArray    my_array;
    
      try
      {
        my_array[100];
      }
      catch (Exception& e)
      {
        e.report();
      }
    }
    
    int            main()
    {
      doSomething();
    }
    
    /* stdout stderr
    Array exception report
    */

  • 맨 처음 catch된 부분만 처리된다.

    #include <iostream>
    
    using namespace std;
    
    class Exception
    {
    public:
      void    report()
      {
        cerr << "Exception report\n";
      }
    };
    
    class ArrayException : public Exception
    {
    public:
      void    report()
      {
        cerr << "Array exception report\n";
      }
    };
    
    class MyArray
    {
      int        data_[5];
    
    public:
      int& operator[] (const int& index)
      {
        if (index < 0 || index >= 5)
          throw ArrayException();
        return data_[index];
      }
    };
    
    void        doSomething()
    {
      MyArray    my_array;
    
      try
      {
        my_array[100];
      }
      catch (Exception& e)
      {
        e.report();
      }
      catch (ArrayException& e)
      {
        e.report();
      }
    }
    
    int            main()
    {
      doSomething();
    }
    
    /* stdout stderr
    Exception report
    */
    warning C4286: 'ArrayException &': is caught by base class ('Exception &') on line 44
    • 따로 처리해야 하는 경우에는 더 작은 범위의 클래스를 위에 두면 된다.

      #include <iostream>
      
      using namespace std;
      
      class Exception
      {
      public:
        void    report()
        {
          cerr << "Exception report\n";
        }
      };
      
      class ArrayException : public Exception
      {
      public:
        void    report()
        {
          cerr << "Array exception report\n";
        }
      };
      
      class MyArray
      {
        int        data_[5];
      
      public:
        int& operator[] (const int& index)
        {
          if (index < 0 || index >= 5)
            throw ArrayException();
          return data_[index];
        }
      };
      
      void        doSomething()
      {
        MyArray    my_array;
      
        try
        {
          my_array[100];
        }
        catch (ArrayException& e)
        {
          e.report();
        }
        catch (Exception& e)
        {
          e.report();
        }
      }
      
      int            main()
      {
        doSomething();
      }
      
      /* stdout stderr
      Array exception report
      */

rethrow

  • catch문 내부에서 throw를 한 번 더 사용할 경우, 값을 전달할 때 차이가 존재한다.

    • throw e; 형태로 직접 값을 넘겨줄 경우

      • 객체 잘림이 발생했을 경우 잘린 상태 그대로 넘어간다.
      #include <iostream>
      
      using namespace std;
      
      class Exception
      {
      public:
        void    report()
        {
          cerr << "Exception report\n";
        }
      };
      
      class ArrayException : public Exception
      {
      public:
        void    report()
        {
          cerr << "Array exception report\n";
        }
      };
      
      class MyArray
      {
        int        data_[5];
      
      public:
        int& operator[] (const int& index)
        {
          if (index < 0 || index >= 5)
            throw ArrayException();
          return data_[index];
        }
      };
      
      void        doSomething()
      {
        MyArray    my_array;
      
        try
        {
          my_array[100];
        }
        catch (Exception& e)
        {
          cout << "doSomething ";
          e.report();
          throw e;
        }
      }
      
      int            main()
      {
        try
        {
          doSomething();
        }
        catch (ArrayException& e)
        {
          cout << "Main ";
          e.report();
        }
        catch (Exception& e)
        {
          cout << "Main ";
          e.report();
        }
      }
      
      /* stdout stderr
      doSomething Exception report
      Main Exception report
      */
    • throw; 형태로 값 없이 키워드만 작성할 경우

      • catch한 값을 그대로 다시 throw해서 객체 잘림이 발생하지 않는다.
      #include <iostream>
      
      using namespace std;
      
      class Exception
      {
      public:
        void    report()
        {
          cerr << "Exception report\n";
        }
      };
      
      class ArrayException : public Exception
      {
      public:
        void    report()
        {
          cerr << "Array exception report\n";
        }
      };
      
      class MyArray
      {
        int        data_[5];
      
      public:
        int& operator[] (const int& index)
        {
          if (index < 0 || index >= 5)
            throw ArrayException();
          return data_[index];
        }
      };
      
      void        doSomething()
      {
        MyArray    my_array;
      
        try
        {
          my_array[100];
        }
        catch (Exception& e)
        {
          cout << "doSomething ";
          e.report();
          throw;
        }
      }
      
      int            main()
      {
        try
        {
          doSomething();
        }
        catch (ArrayException& e)
        {
          cout << "Main ";
          e.report();
        }
        catch (Exception& e)
        {
          cout << "Main ";
          e.report();
        }
      }
      
      /* stdout stderr
      doSomething Exception report
      Main Array exception report
      */
반응형
저작자표시 (새창열림)

'SW개발 > C++' 카테고리의 다른 글

C++ 함수 try (Function try)  (0) 2021.03.22
C++ std::exception  (0) 2021.03.22
C++ 스택 되감기 (Stack Unwinding)  (0) 2021.03.22
C++ 예외 처리의 기본  (0) 2021.03.22
C++ 예외 처리 (Exception Handling)  (0) 2021.03.22
  1. 예외 클래스
  2. 예외 클래스를 상속해서 사용하기
  3. rethrow
'SW개발/C++' 카테고리의 다른 글
  • C++ 함수 try (Function try)
  • C++ std::exception
  • C++ 스택 되감기 (Stack Unwinding)
  • C++ 예외 처리의 기본
Caniro
Caniro
MinimalismCaniro 님의 블로그입니다.
  • Caniro
    Minimalism
    Caniro
  • 전체
    오늘
    어제
    • 전체보기 (319)
      • SW개발 (268)
        • Java Spring (6)
        • C++ (186)
        • Python (21)
        • Linux (16)
        • 알고리즘 (13)
        • Git (4)
        • Embedded (1)
        • Raspberrypi (9)
        • React (3)
        • Web (2)
        • Windows Device Driver (6)
      • IT(개발아님) (46)
        • Windows (26)
        • MacOS (7)
        • Utility (11)
      • 챗봇 짬통 (0)
      • 일상 (2)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    Solaris 10
    스프링 프레임워크 핵심 기술
    windows
    Workspace
    Windows 11
    그림판
    맥북 카카오톡 알림 안뜸
    백기선
    알림
    윈도우 명령어
    로지텍 마우스 제스처
    윈도우
    vscode
    SFC
    시스템 복구
    spring
    logi options
    스프링
    mspaint
    citrix workspace
    java
    unix
    KakaoTalk
    MacOS
    SunOS 5.1
    dism
    제외
    EXCLUDE
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Caniro
C++ 예외 클래스와 상속 (Exception Class and Inheritance)

개인정보

  • 티스토리 홈
  • 포럼
  • 로그인
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.