2016-01-20 64 views
0

我已經爲URLconnection以及Parser類實現了try catch塊,如下所示。如何在一個try/catch塊中捕獲異常和SocketTimeOut異常

try { 
    Url uri = new Url(urlString); 
    Parser parse = new Parser(uri); 
} catch (Exception e) 
{ 
    //ignore some other exceptions 
} 
catch (SocketTimeOutException e) 
{ 
    //I want to catch this exception and do some thing or restart 
    //if it's a timeout issue. 
    //I am using a proxy for the network connection at JVM setting 
    //using setProperty  
} 

所以,我的問題是如何根據該SocketTimeOutException情況採取相應的行動,併爲其他異常忽略。

感謝,

+0

只能將一個趕上(例外五){...}所有其他異常 –

回答

2

爲Java規範說SocketTimeoutException catch子句(http://docs.oracle.com/javase/specs/jls/se7/html/jls-11.html#jls-11.2.3http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.20),首先匹配,首先執行。

只需翻轉你的catch子句:

try { 
Url uri = new Url(urlString); 
Parser parse = new Parser(uri); 
} catch (SocketTimeOutException e) { 
//I want to cache this ecption and do some thing or restart based 
//if its timeout issue 
//am using proxy for the network connection at JVM setting 
//using setProperty 
} catch (Exception e) { 
//ingnore some other excpetions 
} 
1

趕上SocketTimeOutException第一:

try { 
    // do stuff 
} catch (SocketTimeOutException e) { 
    // restart or do whatever you need to do 
} catch (Exception e) { 
    // do something else 
} 
2

把更具體的異常類型上面更爲一般類型的,所以就把上面Exception

1

如何捕捉異常並在一個try/catch塊一個了socketTimeout異常?如果您wan't到只有一個catch塊,那麼你可以像這樣

try { 
      URI uri = new URI(urlString); 
      Parser parse = new Parser(uri); 

      } catch(Exception e) {    
       if (e instanceof SocketTimeoutException) { 
        // do something 
       } 
      } 
+0

非常elegeant後,becuse你知道我之前也在尋找。 +1 – danielad

+0

是的...但推薦的方法是捕捉多個塊的異常。由於問題狀態「1 try/catch」我這樣回答。 –

+0

這有什麼優雅的?這太可怕了,你會做一些事情,因爲異常類的名字以SocketTimeoutException結束?這並不意味着什麼。那麼如果拋出的異常擴展了SocketTimeoutException並且類名以SomethingElseException結束呢? –