有以下代碼,從這里
class Base {
int i;
public:
class BaseExcept {};
Base(int i) : i(i) { throw BaseExcept(); }
};
class Derived : public Base {
public:
class DerivedExcept {
const char* msg;
public:
DerivedExcept(const char* msg) : msg(msg) {}
const char* what() const { return msg; }
};
Derived(int j) try : Base(j) {
// Constructor body
cout << "This won't print" << endl;
}
catch (BaseExcept&) {
throw DerivedExcept("Base subobject threw");;
}
};
int main() {
try {
Derived d(3);
}
catch (Derived::DerivedExcept& d) {
cout << d.what() << endl; // "Base subobject threw"
}
}
我的問題是,為什么這里沒有捕獲拋出的例外
catch (BaseExcept&) {
throw DerivedExcept("Base subobject threw");;
}
但主要問題是什么?
catch (Derived::DerivedExcept& d) {
cout << d.what() << endl; // "Base subobject threw"
}
為什么輸出“Base subobject throw”
按照我的理解,拋出的例外應該在try之后的catch(或者相當于try的函式體)中捕獲,但是沒有,為什么呢?例外的傳播路徑是什么?
那里的代碼
我的問題是這樣的,try catch我以前見過的都有這個表格。
try{}
catch(){}
所以我認為對于以下片段
Derived(int j) try: Base(j) {
// Constructor body
cout << "This won't print" << endl;
}
catch (BaseExcept&) {
throw DerivedExcept("Base subobject threw");;
}
當Derived()拋出例外時,應該由catch (BaseExcept&)下一行的 捕獲,而不是由(Derived::DerivedExcept& d)主函式中的捕獲。但是當我在這里注釋掉它時
catch (Derived::DerivedExcept& d) {
//cout << d.what() << endl; // "Base subobject threw"
}
不會有“基礎子物件拋出”輸出。這與我的預期不同。我正在學習基本的例外知識。我理解錯了嗎
uj5u.com熱心網友回復:
Derived(int j) try : Base(j) {
// Constructor body
cout << "This won't print" << endl;
}
catch (BaseExcept&) { // why the thrown exception is not caught here
throw DerivedExcept("Base subobject threw");;
}
程式輸出的唯一方法Base subobject threw是例外是否在您認為沒有被捕獲的地方被實際捕獲。該字串在程式中的其他任何地方都不存在。
但主要問題是什么?
那是因為您throw在catch. 該例外不會被相同的捕獲catch(在這種情況下會導致無限遞回)。它被try..catch你所擁有的外部抓住了main。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/388757.html
