在catch块中捕获exception后,是否可以再次在try块中执行代码?
我想在捕获exception后再次执行try块中的代码。 这有可能吗?
对于Eg:
try { //execute some code } catch(Exception e) { }
如果捕获到exception,我想再次进入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; } }
已在这些(和其他)链接中回答
在没有goto的情况下编写重试逻辑的更好方法
编写重试逻辑最干净的方法?
如何改进此exception重试方案?
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 } }
还有另一种方法可以做到(虽然正如其他人提到的那样,并不是真的推荐)。 下面是一个使用文件下载重试来更紧密地匹配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; } } }
ole goto
什么问题?
Start: try { //try this } catch (Exception) { Thread.Sleep(1000); goto Start; }