C# 在try-catch块之后继续执行
我想显示“已成功保存”消息,然后继续执行下一个try-catch块。我尝试了“finally”,但它说“control不能离开finally block的主体”。下面是我的代码C# 在try-catch块之后继续执行,c#,exception-handling,csom,C#,Exception Handling,Csom,我想显示“已成功保存”消息,然后继续执行下一个try-catch块。我尝试了“finally”,但它说“control不能离开finally block的主体”。下面是我的代码 try { //some code return ok(new{Message="Successfully saved"}); try { //some code //return ok(new{Message="Successfully created
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语句把你搞砸了。它将带出正在执行的函数,然后返回。finally子句总是在try-catch块(通常用于清理)之后执行,但是由于try中有一个返回,因此在执行时永远不会退出该子句。您可以使用一个try-catch,然后根据catch块中捕获的异常生成一条消息。对于您的消息,这并不是绝对必要的,因为catch块会根据异常情况告诉您哪里出了问题,而返回将告诉您一切正常。听起来您的问题与try-catch块无关,但是你想从一个方法返回,然后再重新输入它。你能按你想要的方式显示代码吗?在您的示例中没有
finally
块,因此很难100%确定问题是什么。我宁愿在catch
块中返回:如果出现问题,继续执行是没有用的为什么在这个方法中捕获异常?如果你马上回来?
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"});