I have a ConnectException that doesn't get caught for any reason

I am working on an Android application that uses sockets. I have a function called initializeStreams () that opens a socket and tries to establish a connection. This function throws a ConnectException if the connection cannot be established. But for some reason, in the code that calls initializeStreams (), which has a catch block for ConnectException, the log prints its own stack trace for the exception instead of going to the catch block. A catch block is never reached at all, although an exact exception is thrown. Here is the code:

Try block:

try { initializeStreams(); /* other code */ } catch (ConnectException e) { Log.i(TAG, "caught connect exception"); } 

initializeStreams ():

  public void initializeStreams() throws ConnectException { try { Log.i(TAG, "Attempting to connect"); requestSocket = new Socket(SERVER_ADDR, PORT); /* other code */ } catch (IOException e) { e.printStackTrace(); } 

I cannot understand this, so any help would be greatly appreciated.

+4
source share
2 answers

You need to bind your exception by throwing it into the catch . Try the following:

 public void initializeStreams() throws ConnectException { try { Log.i(TAG, "Attempting to connect"); requestSocket = new Socket(SERVER_ADDR, PORT); /* other code */ } catch(ConnectException e){ throw e; } catch (IOException e) { e.printStackTrace(); } 
+2
source

ConnectException extends SocketException , which in turn extends IOException, , so the catch for IOException in initializeStreams() catches ConnectException. . I will simply delete this try/catch altogether: there are not many return points purely from this method without connection.

+2
source

All Articles