我的学生提交了一些类似于下面的C ++代码。代码编译并运行,但throw
语句产生以下消息:
在抛出'int'
的实例后终止调用
如果我使函数void
编译器抱怨
无效使用'void'
在包含throw
语句的行(预期)。
class TestClass
{
public:
int MyException()
{
return 0;
}
void testFunc()
{
throw MyException();
}
};
int main(int argc, char** argv)
{
TestClass tc;
tc.testFunc();
return 0;
}
那么,由于代码是“正确的”,C ++如何解释MyException
?
答案 0 :(得分:9)
它调用函数:MyException()
,然后抛出返回的int
。一个更完整的例子:
struct foo
{
int bar(void) const
{
return 123456789;
}
void baz(void) const
{
throw bar();
}
};
int main(void)
{
try
{
foo f;
f.baz(); // throws exception of type int, caught below
}
catch (int i)
{
// i is 123456789
}
}
如果没有try-catch块,异常将从main调用,其中调用terminate()
。
请注意,抛弃不是从std::exception
派生的东西是不受欢迎的。期望您能够通过catch (const std::exception&)
捕获有意义的异常。
答案 1 :(得分:2)
程序终止,因为未捕获异常。试试这个:
int main(int argc, char** argv)
{
try
{
TestClass tc;
tc.testFunc();
}
catch(int)
{
}
return 0;
}