qjwzero 2020-07-08 23:46 采纳率: 0%
浏览 563
已采纳

vs2017在使用try……catch……语句时,报出异常,不执行catch中的语句

vs2017在使用try catch语句时,报出异常,不执行catch中的语句。
设置了/EHa,依然没用。在使用vs6.0时可以正常执行cartch中的语句

#include <iostream>
using namespace std;
int abc(int a, int b, int c)
{
    if (a < 0)
        throw "a<0";
    return a + b + c;
}
int main()
{
    try
    {
        cout << abc(-1, 2, 3) << endl;
    }
    catch (char* e)
    {
        cout << e << endl;
    }
    return 0;
}
  • 写回答

1条回答 默认 最新

  • threenewbee 2020-07-09 00:20
    关注

    不能返回局部变量,因为跨函数,地址无效了。

    #include <iostream>
    #include <cstring>
    using namespace std;
    int abc(int a, int b, int c)
    {
        char * str = new char[100];
        strcpy(str, "a<0");
        if (a < 0)
            throw str;
        return a + b + c;
    }
    int main()
    {
        try
        {
            cout << abc(-1, 2, 3) << endl;
        }
        catch (char* e)
        {
            cout << e << endl;
        }
        return 0;
    }
    

    问题解决的话,请点下采纳。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?