[英]Handling Exceptions in while loops
我想在我的應用程序中記錄一條錯誤消息,以重試調出Web服務,但是我只想在while循環之外一次顯示該錯誤消息,而不是每次重試和失敗時都記錄錯誤,或者我應該做一次環。
int retryCount = x;
int retryWait = y;
int retry = 0;
while (retry <= retryCount)
{
try
{
//get response
}
catch (InvalidOperationException invalid)
{
message = //display status message
}
catch (Exception exc)
{
//display log message
//retry again
retry++;
}
message = "Mamium tries have been exceeded
Logs.WriteError(message);
return false;
}
只需重置消息,然后檢查是否有消息,例如:
while (retry <= retryCount)
{
try
{
message = null;
//get response
}
catch (InvalidOperationException invalid)
{
message = invalid.Message; //display status message
}
catch (Exception exc)
{
//display log message
//retry again
message = exc.Message; //display status message
retry++;
}
if (!string.IsNullOrEmpty(message))
{
message = "Mamium tries have been exceeded"
Logs.WriteError(message);
return false;
}
}
您可以使用您的retry
和retryCount
變量作為樣本,並使用finally
塊進行增量。
{ // main scope
int retry = 0, retryCount = 3;
string message = null;
while (retry < retryCount)
{
try
{
//get response
}
catch (Exception exc)
{
//any error, since you don't need to give another threatment for other erros, just use Exception
message = exc.Message;
}
finally
{
// increment retry anyway
retry++;
}
}
if (retry >= retryCount)
{
message = "Mamium tries have been exceeded"
Logs.WriteError(message);
return false;
}
return true;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.