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.
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();
}