奇怪的C ++异常“定义” [英] Strange C++ exception "definition"
问题描述
我的一名学生提交了一些类似于以下的C ++代码。代码编译并运行,但 throw
语句产生以下消息:
终止调用后抛出一个'int'的实例
如果我使函数 void
编译器抱怨
无效使用'void'
在包含 throw
语句(预期)的行。
code> 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 $>由于代码是正确的?
它调用函数: code> MyException(),然后抛出返回的 int
。一个更完整的例子:
struct foo
{
int bar(void)const
{
return 123456789;
}
void baz(void)const
{
throw bar();
}
};
int main(void)
{
try
{
foo f;
f.baz(); //抛出类型int的异常,在
下方
catch(int i)
{
//我是123456789
}
}
没有try-catch块,异常传播出主,其中 请注意,抛出不从 A student of mine submitted some C++ code similar to the following one. The code compiles and runs, but the terminate called after throwing an instance of 'int' If I make the function invalid use of ‘void’ on the line that contains the So, how does C++ interpret It calls the function: Without the try-catch block, the exception propagates out of main, where Note that throwing things that don't derive from 这篇关于奇怪的C ++异常“定义”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! terminate( )
std :: exception $ c派生的东西$ c>皱起眉头。预期您可以通过
catch(const std :: exception&)
捕获有意义的异常。throw
statement produces the following message:
void
the compiler complains
throw
statement (expectedly).class TestClass
{
public:
int MyException()
{
return 0;
}
void testFunc()
{
throw MyException();
}
};
int main(int argc, char** argv)
{
TestClass tc;
tc.testFunc();
return 0;
}
MyException
since the code is "correct" ?MyException()
, then throws the returned int
. A more complete example: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
}
}
terminate()
is called.std::exception
is frowned upon. It's expected that you be able to catch meaningful exceptions by catch (const std::exception&)
.