I was experimenting with Apache HTTP client library in Eclipse
<dependency org="org.apache.httpcomponents" name="httpclient" rev="4.3.1"/>
and following snippet of code throws checked Exception and needs to be handled.
HttpResponse response = httpClient.execute(httprequest);
Eclipse gives 3 suggestions
Add throws Exception -
throws ClientProtocolException, IOException
(Works fine)Surround with try catch -
try { HttpResponse response = httpClient.execute(httprequest); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }
(Also works fine)
Surround with try/multicatch
try { HttpResponse response = httpClient.execute(httprequest); } catch (ClientProtocolException | IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }
3rd option gives error
The exception ClientProtocolException is already caught by the alternative IOException
I saw the source code for ClientProtocolException
and it IOException
. As far as my understanding goes when catching multiple Exception we can catch more generic Exception below more specific one. So we can't catch ClientProtocolException
after catching IOException
.
So why does this happen in multi try-catch? And if it is not suppose to work why does Eclipse give that suggestion in 1st place?