[英]Resume code in try block after exception is caught
99%的時間,您想在try-catch
之后重新運行代碼塊,而不是異常行。
如果您需要從該行開始運行,那么這表明您可以將代碼帶入僅封裝該代碼的另一種方法中(也可以將try-catch
移到那里)。
我會建議的是這樣的:
void method(){
try{
codeline1;
codeline2;
codeline3;
codeline4;
}
catch(Exception ex)
{
restorClassStateBeforeCodeLine1();
method();
}
}
通過這一點,我建議將您的整個try-catch
用單獨的方法進行。
等待隨機間隔也是一個壞習慣。 您永遠不會知道10秒鍾是正確的還是每次都正確。
我建議的另一種方法是:
label: {
try {
...
if (condition)
break label;
...
} catch (Exception e) {
...
}
}
它使用Java標簽重試該部分。 我從未嘗試過,但是break
可以在try
catch
了,標簽可以進行。
我認為不可能從catch塊內部返回到try塊中的特定行。 因為執行throw
時,運行時系統將從調用堆棧中彈出框架,尋找與拋出的異常匹配的異常處理程序,並且一旦從堆棧中彈出框架,它就消失了。 有關此的更多信息,請參見此處
您可以做的是在catch塊內調用導致throw
的方法。 但這意味着它將從頭開始執行您的方法,因此也許您想嘗試重新排列代碼,以免引起任何其他問題。 編輯:另一個答案完全說明了我的意思。
這個簡單的程序遍歷數組值,測試每個數組,直到找到不會產生異常的值
public static void main(String[] args) {
int[] array=new int[]{0,0,0,0,5};
for(int i=0; i<array.length;i++) {
try {
System.out.println(10/array[i]);
break;
} catch(Exception e) {
try { Thread.sleep(1000); } catch(Exception ignore){}
}
}
}
while(true){
try{
//actions where some exception can be thrown
break;//executed when no exceptions appeared only
}
catch(YourException e){
Thread.sleep(10_000);
}
}
當您尚未執行指令時,將重復此循環。 成功執行try塊中的代碼后,中斷將有助於您退出此循環
因為您說的是遇到間歇性錯誤的代碼只有2行,所以請嘗試類似的操作。
public static void main(String... args)
{
try
{
//Some Logic
//Error throwing logic in method
while(!doLogic())
{
Thread.sleep(1000);//Sleep here or in doLogic catch
}
//Continuing other logic!
}
catch(Exception e)
{
e.printStackTrace();
}
}
static Integer i = null;
public static boolean doLogic()
{
try
{
//Lines that throw error
System.out.println(i.toString());//NPE First run
}
catch (Exception e)
{
i = 1;
return false;
}
return true;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.