2016-01-20 67 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结束呢? –