[英]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.