저는 C++ 예외 처리를 처음 접했습니다. 내 마음의 규칙은 다음 이 함수가 호출 종료 예외의 어떤 핸들러가 호출 체인 (함수 호출 스택)에서 발견되지 않는 경우생성자에서 발생한 예외 처리기는 무엇입니까?
- 점이다.
- 핸들러는 캐치 {} 블록이다.
그러나 다음 동작은 이해할 수 없습니다. X의 생성자에 던져 예외가 두 번 (. 또는 처리) 잡은 것 같다 :
#include <iostream>
#include <exception>
using namespace std;
struct X {
X() try { throw exception(); }
catch (exception &e) {
cout << "Exception caught in constructor!" << endl;
}
};
int main() {
try {
throw exception();
}
catch (exception &e) {
cout << "Exception caught in function." << endl;
}
cout << "After Exception being caught in function" << endl;
try {
X x;
}
catch (exception &e) {
cout << "Why exception is caught again!" << endl;
}
return 0;
}
출력은
Exception caught in function. After Exception being caught in function Exception caught in constructor! Why exception is caught again!
질문 1입니다. 또는 생성자 다음에 catch() 블록이 생성자의 예외 처리기로 계산되지 않는 이유는 무엇입니까?
나는 try{}
블록에 X x;
을 넣고 main()
에 잡을 수없는 경우, 출력은 다음과 같습니다 우리가 할 때 호출는 기본 (종료 IS) 기능 :
Exception caught in function. After Exception being caught in function Exception caught in constructor! terminate called after throwing an instance of 'std::exception' what(): std::exception Aborted (core dumped)
질문 2 try 블록에 X x;
이 없습니까?
관련 항목 : http://stackoverflow.com/a/19687623/952747 – deepmax
@MM. 고마워. 나는 수색했지만 그 질문을 놓쳤다. –