Here’s some code from an FTP application I’m working on. The first method comes from an interface which is being triggered by a class which is monitoring server output.
@Override
public void responseReceived(FTPServerResponse event) {
if (event.getFtpResponseCode() == 227) {
try {
setupPassiveConnection(event.getFullResponseString());
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
It invokes the second setupPassiveConnection() which throws some Exceptions.
public void setupPassiveConnection(String serverReplyString) throws UnknownHostException, IOException {
String passiveInfo[] = serverReplyString.substring(
serverReplyString.indexOf("(") + 1,
serverReplyString.indexOf(")")).split(",");
int port = (Integer.parseInt(passiveInfo[4]) * 256)
+ (Integer.parseInt(passiveInfo[5]));
String ip = passiveInfo[0] + "." + passiveInfo[1] + "."
+ passiveInfo[2] + "." + passiveInfo[3];
passiveModeSocket = new Socket(ip, port);
if( passiveModeSocket != null )
isPassiveMode();
}
As the Exceptions can’t be rethrown through the first method what would be a proper way to rewrite this?
Do you mean that the first code block is inside a class that implements an interface that specifies
responseReceivedwith no throws clause, so you can’t rethrow?In that case, your class must store the result and provide an API via which clients can retrieve the response, i.e. a
getResponseCode()method.Take a look at java.util.concurrent classes
ExecutorServiceandFuture.