C++

C++사용자 정의 예외

김구티2 2024. 4. 25. 19:26

우리는 클래스에 예외 처리를 사용할 수도 있다. 심지어 사용자 정의 클래스 유형의 예외를 던질 수도 있다. try 블록 내에 demo 클래스 유형의 예외를 던지는 경우 작성할 수 있다.

 

throw demo();


단일 클래스로 예외 처리를 구현하는 프로그램 예시:

#include <iostream>
using namespace std;

class demo {
};

int main()
{
     try {
          throw demo();
     }

     catch (demo d) {
        cout << "Caught exception of demo class \n";
     }
}

 

출력:

Caught exception of demo class

 

위 프로그램에서는 빈 클래스를 선언했다. try 블록에서 우리는 demo 클래스 유형의 개체를 던진다. 이에 try 블록은 개체를 잡고 표시한다.

 

두 개의 클래스로 예외 처리를 구현하는 프로그램:

#include <iostream>
using namespace std;

class demo1 {
};

class demo2 {
};

int main()
{
     for (int i = 1; i <= 2; i++) {
          try {
               if (i == 1)
                    throw demo1();

               else if (i == 2)
                    throw demo2();
          }

          catch (demo1 d1) {
               cout << "Caught exception of demo1 class \n";
          }

          catch (demo2 d2) {
               cout << "Caught exception of demo2 class \n";
          }
     }
}

 

출력:

Caught exception of demo1 class
Caught exception of demo2 class

 

한편, 상속의 도움으로 예외 처리를 구현할 수도 있다. 파생 클래스가 던진 상속 객체가 첫 번째 캐치 블록에 걸리는 경우를 생각해 볼 수 있다.

 

예시:

#include <iostream>
using namespace std;

class demo1 {
};

class demo2 : public demo1 {
};

int main()
{
     for (int i = 1; i <= 2; i++) {
          try {
               if (i == 1)
                    throw demo1();

               else if (i == 2)
                    throw demo2();
          }

          catch (demo1 d1) {
               cout << "Caught exception of demo1 class \n";
          }
          catch (demo2 d2) {
               cout << "Caught exception of demo2 class \n";
          }
     }
}

 

출력:

Caught exception of demo1 class
Caught exception of demo1 class

 

이 프로그램은 이전 프로그램과 비슷하지만, 여기서는 demo1의 파생 클래스로 demo2를 만들었다. demo1의 catch 블록이 먼저 작성된다. demo1이 demo2의 기본 클래스이므로, demo2 클래스에서 던진 개체는 첫 번째 캐치 블록으로 처리된다. 이것이 출력이 표시된 이유인 것이다.

 

예외 처리는 생성자를 사용하여 구현할 수도 있다. 생성자로부터 어떤 값도 반환할 수 없지만, 블록을 시도하여 얻을 수 있다.

 

예시:

#include <iostream>
using namespace std;

class demo {
     int num;

public:
     demo(int x)
     {
          try {

               if (x == 0)
                    // catch block would be called
                    throw "Zero not allowed ";

               num = x;
               show();
          }

          catch (const char* exp) {
               cout << "Exception caught \n ";
               cout << exp << endl;
          }
     }

     void show()
     {
          cout << "Num = " << num << endl;
     }
};

int main()
{

     // constructor will be called
     demo(0);
     cout << "Again creating object \n";
     demo(1);
}

 

출력:

Exception caught
Zero not allowed
Again creating object
Num = 1

 

x = 0 의 예외가 던져지고 catch block 이 호출되고, x = 1 의 경우에는 예외가 생성되지 않는다.

728x90