c++用什么替代goto处理错误返回

c风格用goto处理函数的错误返回清理工作等,c++是否只能用异常?do while结构遇到逻辑里面有循环就歇菜了。。

 int foo()
{
    ReportInfo rinfo;
    int ret = 0;

    ret = dosth1();
    if (ret != 0)
    {   
        goto error_handler;
    }   

    handle_logic1(&rinfo);

    ret = dosth2();
    if (ret != 0)
    {   
        goto error_handler;
    }   

    handle_logic2(&rinfo);

error_handler:

    rinfo.set_ret(ret);
    ReportTo(rinfo);

    return ret;
}

好好设计吧,
goto的存在有时还是比较直观的

一般错误处理可以用exception吧

int foo()
{
    ReportInfo rinfo;
    int ret = 0;

    try {
    ret = dosth1();
    if (ret != 0)
    {   
        throw std::exception();
    }   

    handle_logic1(&rinfo);

    ret = dosth2();
    if (ret != 0)
    {   
        throw std::exception();
    }   

    handle_logic2(&rinfo);

    }
        catch (std::exception e) {

    rinfo.set_ret(ret);
    ReportTo(rinfo);

    }
    return ret;
}

异常有什么不好吗?若确定不要异常,可以把error处理语句做成个函数,调用后直接return。

C++里面只能用exception来处理了,比较好实现。不然就保留goto,只要不混乱,也是可以理解的

goto语句等你工作了就知道了,c++中绝对不会让你用的,否则老程序员会把你埋汰死,goto语句造成你的理解流程乱,c++中可以使用try catch,而且c++中没有什么逻辑是非goto语句不用的。

你可以试试setjump()和longjump()函数其功能类似goto但比goto还强大