[英]Handling Exceptions in while loops
I want to log an error message in my application for a retry to call out the webservice but I only want to disply the error message once outside of the while loop instead of logging the error everytime it retries and fails or should I do a do while loop. 我想在我的应用程序中记录一条错误消息,以重试调出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;
}
Simply reset the message, and check if there is one, so something like: 只需重置消息,然后检查是否有消息,例如:
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;
}
}
You could use your retry
and retryCount
variables, for sample, and use finally
block to increment anyway. 您可以使用您的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.