繁体   English   中英

在 try catch 块后继续执行

[英]continue execution after try catch block

我想显示“成功保存”消息,然后想继续下一个 try-catch 块。 我试过'finally',但它说'控制不能离开finally 块的主体'。 以下是我的代码。

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"});
}

谁能帮帮我吗?

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

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;
}

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

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 块中输入的代码

但是无论在 try 或 catch 块中输入的代码如何,varResult1 都返回成功

为什么不return最后

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"});

return 语句是什么让你搞砸了。 它会将您带出正在执行的函数,然后返回。 finally 子句将始终在 try-catch 块(通常用于清理)之后执行,但由于您在 try 中有返回,因此您永远不会在执行中退出该子句。 您可以使用单个 try-catch,然后根据在 catch 块中捕获的异常生成一条消息。 对于您的消息,它不是非常必要的,因为 catch 块会根据异常告诉您哪里出错了,而到达返回值会告诉您一切正常。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM