奇怪的C ++异常“定义” [英] Strange C++ exception "definition"

查看:101
本文介绍了奇怪的C ++异常“定义”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的一名学生提交了一些类似于以下的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块,异常传播出主,其中 terminate( )

请注意,抛出不从 std :: exception 皱起眉头。预期您可以通过 catch(const std :: exception&)捕获有意义的异常。


A student of mine submitted some C++ code similar to the following one. The code compiles and runs, but the throw statement produces the following message:

terminate called after throwing an instance of 'int'

If I make the function void the compiler complains

invalid use of ‘void’

on the line that contains the 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;
}

So, how does C++ interpret MyException since the code is "correct" ?

解决方案

It calls the function: 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
    }
}

Without the try-catch block, the exception propagates out of main, where terminate() is called.

Note that throwing things that don't derive from std::exception is frowned upon. It's expected that you be able to catch meaningful exceptions by catch (const std::exception&).

这篇关于奇怪的C ++异常“定义”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆