尝试catch块后继续执行

时间:2016-05-27 12:32:23

标签: c# exception-handling csom

我想展示"成功保存"消息,然后想继续下一个try-catch块。我终于试过了#39;但它说“控制不能离开最终阻挡的身体”。以下是我的代码。

try
{
    //some code

    return ok(new{Message="Successfully saved"});

    try
    {
        //some code
        //return ok(new{Message="Successfully created site"});
    }
    catch(Exception ex)
    {
        //return ok(new {Message="failed to create site"});
    }
}
catch(Exception ex)
{
//return ok(new {Message="failed to save"});
}

任何人都可以帮助我吗?

5 个答案:

答案 0 :(得分:1)

为什么不先将结果存储到变量中?

private WhatEverType MyMethod()
{
    WhatEverType result = default(WhatEverType);
    try
    {
        //some code

        result = ok(new{Message="Successfully saved"});

        try
        {
            //some code
            result = ok(new{Message="Successfully created site"});
        }
        catch(Exception ex)
        {
            result = ok(new {Message="failed to create site"});
        }
    }
    catch(Exception ex)
    {
        result = ok(new {Message="failed to save"});
    }
    return result;
}

答案 1 :(得分:0)

您将从第一个try块返回,因此您的代码将不再执行其他try-catch块。我建议将返回消息值存储/附加到字符串中(而不是自己返回),最后在finally块中显示最终成功(或错误)的内容。

答案 2 :(得分:0)

public return-type method()
{
    var-type varResult;
    var-type varResult1;

    try
    {
        // code
        varResult = successfully saved

        try
        {
            //code
            varResult = unsuccessfully saved
        }
        catch(Exception ex)
        {
            varResult = successfully saved
        }
    }
    catch(Exception ex)
    {
        result = varResult = unsuccessfully saved
    }
    finally
    {
        varResult1 = success
    }

    return varResult1
}

这里varResult根据代码的流程返回它依赖于在try或catch块中输入的代码

但varResult1返回成功,无论代码进入try或catch块

答案 3 :(得分:0)

为什么不是try { //some code //DONE: no return here - we're not ready to return, but want to continue try { // some code //DONE: no return here - we're not ready to return, but want to continue } catch (Exception ex) //TODO: do not catch Exception, but more specific exception { return ok(new {Message="failed to create site"}); } } catch (Exception ex) //TODO: do not catch Exception, but more specific exception { return ok(new {Message="failed to save"}); } // but here return ok(new{Message="Successfully saved;Successfully created site"}); ,而是结束

$('#myModal2').on('show.bs.modal', function (e) {
    $('#myModal').modal('hide');
$('body').css("overflow","hidden");
})
.on('hide.bs.modal', function (e) {
    // @todo reload the job
    $('#myModal').modal('show');
});
$('#myModal').on('show.bs.modal', function (e) {
    // @todo reload the job
$('body').css("overflow","hidden");
})
.on('hide.bs.modal', function (e) {
    // @todo reload the job
$('body').css("overflow","visible");
});

答案 4 :(得分:0)

返回声明正在弄乱你。它将把你正在执行的功能带走,然后返回。 finally子句总是在try-catch块之后执行(通常用于清理),但由于你在try中有一个return,所以你永远不会在执行中退出该子句。您可以使用单个try-catch,然后根据catch块中捕获的异常生成一条消息。对于你的消息,这不是非常必要的,因为你会告诉你哪里出错了,这取决于异常并且到达回报会告诉你一切正常。