【发布时间】:2020-11-15 13:48:37
【问题描述】:
class base {
public:
base() : value(int()) {
throw true;
}
private:
int value;
};
class derived : public base {
public:
derived() : base() { // base class constructor called, `value` to be initialized
// I want this to propagate (rethrow) base class exception... how do I do it?
}
};
int main(){
try {
derived a;
}
catch(bool){
// Base class exception to be caught
}
}
在上面的例子中已经说过了。如何传播(重新抛出)基类异常?
我试试这个可憎的:
class base {
public:
base() : value(int()) {
throw true;
}
private:
int value;
};
class derived : public base {
public:
derived() : try { base() } catch(bool) {throw;} {
// ...
}
};
int main(){
try {
derived a;
}
catch(bool){
// Base class exception to be caught
}
}
不编译,给出语法错误。非常期待。解决办法是什么?
不要继续阅读。需要更多字符。输入更多字符。
【问题讨论】:
-
好吧,你说我必须
catch。我如何以这种方式捕捉它们的异常:derived() : try { base() } catch(bool){throw;} {}。我认为这是一个非常聪明的主意,尽管我的兄弟们称我为白痴 -
你是个很聪明的人。我尝试
try和catch,因为它写在上面的评论中。 Tho' me homies callin' me bit粗。我的代码有什么问题? -
不编译,伙计
-
使用这个:
derived() try : base() { } catch(bool) { throw; }...评论中的语法排列错误。 -
@user3600124 例如见Function-try-block。另外请注意,在构造函数周围的
catch块内,您不应引用base或derived中的任何内容,因为此时没有正确构造任何对象。