• 카테고리

    질문 & 답변
  • 세부 분야

    프로그래밍 언어

  • 해결 여부

    미해결

throw; vs throw e;의 차이가 궁금합니다.

20.02.12 12:57 작성 조회수 192

0

/*

예외 클래스와 상속

*/

#include <iostream>

using namespace std;

class Exception

{

public:

virtual void report() const

{

cerr << "Exception report" << endl;

}

};

class ArrayException : public Exception

{

public:

void report() const override

{

cerr << "Array exception" << endl;

}

};

class MyArray

{

private:

int m_arr[5];

public:

int& operator[] (const int& index)

{

//if (index < 0 || index > 4) throw - 1;

if (index < 0 || index > 4) throw ArrayException();

return m_arr[index];

}

};

void doSomething()

{

MyArray my_arr;

try

{

my_arr[100]; //멤버함수에서 throw를 던져도 받을 수 있음.

}

catch (const int& x)

{

cerr << "Exception" << x << endl;

}

catch (Exception & e)// Exception & e = ArrayException();

{

cout << "doSomething()" << endl;

e.report();

//rethorw

throw e; //하면 다형성이 풀림?

//throw;

}

}

int main()

{

try

{

doSomething();

}

catch (Exception & e)

{

cout << "main()" << endl;

e.report();

}

return 0;

}

throw ArrayException()하고 두번의 catch문을 모두 Exception으로 받게 해놨습니다. 그런데 처음 catch에서는 다형성 성질에 맞게 자식클래스의 report를 실행했는데 throw e로 했을 경우에는 자식클래스의 report가 아닌 부모클래스의 report를 실행합니다. 거기다가 throw;로 했을 경우에는 정상적으로 자식클래스의 report를 실행합니다.

1. throw e;로 했을 경우에는 왜 다형성이 풀리는 건가요?

2. throw;랑 throw e; 랑 차이는 무엇인가요?

답변 1

답변을 작성해보세요.

1

강의에서 설명을 드렸던 것 같은데 일단 차이를 알고 계시는 것은 중요합니다. 아래 링크도 참고해보세요.

https://stackoverflow.com/questions/1833982/in-c-is-there-a-difference-between-throw-and-throw-ex