2013-07-29 10 views
0

我有一個Java程序,試圖從服務器列表中收集某個rss訂閱源。如果有任何失敗,(認證,連接等),我想拋出一個異常,基本上帶我回到主循環,我可以捕捉它,在日誌中顯示一些信息,然後移動嘗試下一個服務器在循環。大多數例外似乎都是致命的,儘管......即使他們並不真正需要。我相信我看到的例外不是致命的......但是不確定。我試圖搜索,但我可能使用了錯誤的術語。Java中的異常(可恢復vs致命)

有人能幫助我指出正確的方向嗎?我可以拋出哪些特殊類型的異常,這些異常是可以恢復的,而不是將整個程序停下來?

回答

1

無論您拋出的異常類型如何,它都會調用堆棧直到被捕獲。所以你只需要抓住它:

for (Server server : servers) { 
    try { 
     contactServer(server); 
    } 
    catch (MyCustomException e) { 
     System.out.println("problem in contacting this server. Let's continue with the other ones"); 
    } 
} 

閱讀Java tutorial about exceptions

1

錯誤:

An Error "indicates serious problems that a reasonable application should not try to catch."

例外:

An Exception "indicates conditions that a reasonable application might want to catch."

例外總是意味着要採,不管勾選或者雖然它可能永遠不會處理它們,但它應該是。而另一方面,錯誤必須是致命的。然而,即使錯誤可以被處理,但它寧願只是花哨的方式說「它死」

也許你會想看看Exception VS Error

+0

只需連接ISN這不是一個好主意。我會在你的文章中加入重要的細節。 – hexafraction

2

沒有Exception需要是致命的。 (Errors然而,它們是致命的,不要抓住它們)。你所要做的就是在某處找到Exception,這不是致命的。

try 
{ 
    riskyMethod(); 
} 
catch (ReallyScaryApparentlyFatalException e) 
{ 
    log(e); 
    // It's not fatal! 
} 
+0

錯誤的子類可以被假設*捕獲嗎?更好的是,如果在類加載器中遇到錯誤,該類如何用來將錯誤作爲可拋出的加載進行分派? – hexafraction

+1

任何事物都可以被抓住catch(Throwable t)' – zapl

+0

任何'Throwable'都可以被抓住。 – rgettman

2

本身沒有「不可恢復的例外」。在Java中,如果註冊爲一個「例外」你可以捕捉它:

try { 
    // Attempt to open a server port 
} catch (SecurityException ex) { 
    // You must not be able to open the port 
} catch (Exception ex) { 
    // Something else terrible happened. 
} catch (Throwable th) { 
    // Something *really* terrible happened. 
} 

你可能想要什麼,如果你正在創建連接的應用程序服務器,這樣的事情:

for(Server server : servers) { 
    try { 
    // server.connectToTheServer(); 
    // Do stuff with the connection 
    } catch (Throwable th) { 
    //Log the error and move along. 
    } 
}