I have a ConnectException that isn't being caught for some reason
-
18-06-2021 - |
Question
I'm working on an Android application that uses sockets. I have a function called initializeStreams() which opens the socket and attempts a connection. This function throws a ConnectException if the connection could not be established. But for some reason, in the code that calls initializeStreams(), which has a catch block for ConnectException, the log prints out its own stack trace for the exception instead of going to the catch block. The catch block is never reached at all, even though the exact exception is being thrown. Here's the code:
The 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 can't figure this out, so any help would be much appreciated.
Solution
You need to chain your Exception throwing it in the catch
block. 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();
}
OTHER TIPS
ConnectException
extends SocketException
which in turn extends IOException,
so the catch for IOException
in initializeStreams()
catches the ConnectException.
I would just remove that try/catch
block altogether: there's not much point in returning cleanly from this method without a connection.