Programming/C,CPP,CS

CPP 예외처리

TanSanC 2012. 9. 23. 15:39

#include <iostream>

#include <string>

#include <exception>

using namespace std;

class UserException : public logic_error

{

public:

    int num1;

    int num2;

    UserException(const int num1, const int num2)

        : logic_error("잘못된인수값")

    {

        this->num1 = num1;

        this->num2 = num2;

    }

    int getNum1(){ return num1; }

    int getNum2(){ return num2; }

};

int divide(int n1, int n2)

{

    UserException ue(n1, n2);

    if( n2 == 0 )

        throw ue;

    int result = n1 / n2;

    return result;

}

 

int main()

{

    int n1, n2;

    cout << ": ";

    cin >> n1;

    cout << ": ";

    cin >> n2;

    try

    {

        cout << divide(n1, n2);

    }

    catch(UserException n)

    {

        cout << "0으로나눌수없습니다." << endl;

        cout << "n1 = " << n.getNum1() << endl;

        cout << "n2 = " << n.getNum2() << endl;

    }  

    return 0;

}