[C++] 예외 클래스 만들기

Seongcheol Jeon·2025년 6월 30일
0

CPP

목록 보기
41/47
post-thumbnail

예외 클래스 만들기

예외 값으로 int, double 등의 기본 타입을 사용할 때보다 클래스를 사용하면 catch() {} 블록에 더 많은 정보를 전달 할 수 있다.

다음은 예외 값으로 사용할 클래스를 작성하여 실행하는 예이다.

#include <iostream>
#include <string>

using namespace std;


class MyException
{
public:
    MyException(int n, string f, string m)
    {
        lineNo = n, func = f; msg = m;
    }

    void print() const
    {
        cout << func << " : " << lineNo << ", " << msg << endl;
    }

private:
    int lineNo;
    string func, msg;
};


class DivideByZeroException : public MyException
{
public:
    DivideByZeroException(int lineNo, string func, string msg)
        : MyException(lineNo, func, msg) { }
};


class InvalidInputException : public MyException
{
public:
    InvalidInputException(int lineNo, string func, string msg)
        : MyException(lineNo, func, msg) { }
};


int main()
{
    int x, y;

    try
    {
        cout << "Enter two integers: ";
        cin >> x >> y;
        if (x < 0 || y < 0)
        {
            throw InvalidInputException(__LINE__, "main()", "음수 입력 예외 발생!");
        }
        if (y == 0)
        {
            throw DivideByZeroException(__LINE__, "main()", "0으로 나누는 예외 발생!");
        }

        cout << static_cast<double>(x) / static_cast<double>(y) << endl;
    }
    catch (const DivideByZeroException& e)
    {
        e.print();
    }
    catch (const InvalidInputException& e)
    {
        e.print();
    }

    return 0;
}


/* 결과
Enter two integers: 2 8
0.25

Enter two integers: 15 -5
main() : 52, 음수 입력 예외 발생!

Enter two integers: 11 0
main() : 56, 0으로 나누는 예외 발생!
*/

0개의 댓글