我的一个学生提交了一些类似于下面的C++代码.代码编译并运行,但该throw
语句产生以下消息:
抛出'int'实例后调用terminate
如果我创建函数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;
}
Run Code Online (Sandbox Code Playgroud)
那么,MyException
由于代码是"正确的" ,C++如何解释?
它调用函数: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
}
}
Run Code Online (Sandbox Code Playgroud)
如果没有try-catch块,异常会从main传播出来,在那里terminate()
调用.
请注意,抛弃不是从中衍生出来的东西std::exception
是不受欢迎的.期望您能够捕获有意义的异常catch (const std::exception&)
.