簡體   English   中英

在catch塊中捕獲異常后,是否可以再次在try塊中執行代碼?

[英]Is it possible to execute the code in the try block again after an exception in caught in catch block?

我想在捕獲異常后再次執行try塊中的代碼。 這有可能嗎?

對於Eg:

try
{
    //execute some code
}
catch(Exception e)
{
}

如果異常被捕獲,我想再次進入try塊以“執行一些代碼”並再次嘗試執行它。

把它放在一個循環中。 可能會在布爾標志周圍循環一圈,以控制何時最終要退出。

bool tryAgain = true;
while(tryAgain){
  try{
    // execute some code;
    // Maybe set tryAgain = false;
  }catch(Exception e){
    // Or maybe set tryAgain = false; here, depending upon the exception, or saved details from within the try.
  }
}

小心避免無限循環。

更好的方法可能是將“某些代碼”放在自己的方法中,然后可以在try和catch中調用該方法。

如果將塊包裝在方法中,則可以遞歸調用它

void MyMethod(type arg1, type arg2, int retryNumber = 0)
{
    try
    {
        ...
    }
    catch(Exception e)
    {
        if (retryNumber < maxRetryNumber)
            MyMethod(arg1, arg2, retryNumber+1)
        else
            throw;
    }
}

或者你可以在循環中完成它。

int retries = 0;

while(true)
{
    try
    {
        ...
        break; // exit the loop if code completes
    }
    catch(Exception e)
    {
        if (retries < maxRetries)
            retries++;
        else
            throw;
    }
}
int tryTimes = 0;
while (tryTimes < 2) // set retry times you want
{
    try
    {
        // do something with your retry code
        break; // if working properly, break here.
    }
    catch
    {
        // do nothing and just retry
    }
    finally
    {
        tryTimes++; // ensure whether exception or not, retry time++ here
    }
}

ole goto什么問題?

 Start:
            try
            {
                //try this
            }
            catch (Exception)
            {

                Thread.Sleep(1000);
                goto Start;
            }

還有另一種方法可以做到這一點(盡管正如其他人提到的那樣,並不是真的推薦)。 下面是一個使用文件下載重試的示例,以更緊密地匹配VB6中Ruby中的retry關鍵字。

RetryLabel:

try
{
    downloadMgr.DownLoadFile("file:///server/file", "c:\\file");
    Console.WriteLine("File successfully downloaded");
}
catch (NetworkException ex)
{
    if (ex.OkToRetry)
        goto RetryLabel;
}

這應該工作:

count = 0;
while (!done) {
  try{
    //execute some code;
    done = true;
  }
  catch(Exception e){
  // code
  count++;
  if (count > 1) { done = true; }
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM