注册 登录
编程论坛 C++教室

小白求助 关于抛异常的问题

d7se123 发布于 2020-05-10 11:58, 2380 次点击
#include "iostream"
using std::endl;
using std::cin;
using std::cout;

double divided(int a, int b)
{
    if (b == 0)
    {
        throw a;
    }
    return a / b;
}

void myDivided(int a, int b)
{
    try
    {
        divided(a, b);
    }
    catch (...)
    {
        cout << "我接收了divided的异常,但是我没处理\n";
        throw;//问题1: 这里throw之后运行成功
    }
}

void main()
{
    try
    {
        myDivided(10, 2);
        myDivided(40, 0);
    }
    catch (...)
    {
        cout << "其他异常\n";
    }
    system("pause");
}




#include "iostream"
using std::endl;
using std::cout;
using std::cin;

class Test
{
private:
    int a;
    int b;
public:
    Test(int a, int b)
    {
        this->a = a;
        this->b = b;
    }
    ~Test()
    {
        cout << "析构函数执行了\n";
    }
};

void objPlay()
{
    Test t1(11, 22);
    Test t2(33, 44);
    cout << "准备抛异常\n";
    throw;//问题:对比上面的运行成功 这里直接throw运行失败,是怎么一回事啊?
}

void main()
{
    try
    {
        objPlay();
    }
    catch (...)
    {
        cout << "未知类型异常\n";

    }
    system("pause");
}
7 回复
#2
雪影辰风2020-05-10 12:58
objPlay里边儿的throw没有指明表达式,还不在catch里,就无法抛出异常,所以后边儿catch才无法接收异常
【这东西我不太了解,网上资料结合起来的,得出的结论,不保证正确。】
#3
d7se1232020-05-10 16:43
回复 2楼 雪影辰风
不管怎么说 谢谢大佬了
#4
rjsp2020-05-10 16:45
不叫运行成功、运行成功,叫编译成功、编译失败。
在 catch块 中 throw语句后面不写任何exception,就是 throw 被catch的那个 exception。
#5
rjsp2020-05-10 16:51
这个语法是必须的,尤其是在 catch (...) 中,你不知道是什么类型的异常,却又想转发它。
#6
d7se1232020-05-11 11:17
回复 4楼 rjsp
谢谢大佬了  你是说在catch里只有throw 表示继续抛出前一个的异常吗?
#7
rjsp2020-05-11 16:13
catch (...)
{
    throw; // 这个 重新抛出 被 catch 的那个异常
}
#8
d7se1232020-05-11 17:09
回复 7楼 rjsp
谢谢了 原来是版主驾到 有失远迎
1