Our Products:   CompleteFTP  edtFTPnet/Free  edtFTPnet/PRO  edtFTPj/Free  edtFTPj/PRO
0 votes
9.7k views
in Java FTP by
I'm wondering what is going on in case of exception - e.g. I have something like this

FTPClient ftp = null;

try {
// set up client
ftp = new FTPClient( host, portInt.intValue() );

...................

// Shut down client
ftp.quit();
}
catch (Exception e) {
errorMessage = e.getMessage();
}

If exception happens in the middle of try {} - ftp.quit() is never called and my question is - who is going to close connection in this case? Do I have to do it myself in Catch (and that means another try catch inside catch) or before exception is thrown the connection is closed?

Thanks a lot!

6 Answers

0 votes
by (162k points)
Do the quit() in a finally block.

If exception happens in the middle of try {} - ftp.quit() is never called and my question is - who is going to close connection in this case? Do I have to do it myself in Catch (and that means another try catch inside catch) or before exception is thrown the connection is closed?

Thanks a lot!
0 votes
by
Thanks a lot!
0 votes
by
After some thinking -

ftp.quit(); throws IOException, so I have to try catch it if I don't want to throw it to the caller and it does not matter if I do it in finally or in first catch... Just to understand it 100% - I absolutely have to do ftp.quit() or the session will not be closed?
0 votes
by (162k points)
It is a bit tricky. You should do quit() if you can. The problem is, if you get an IOException, then quit() may not work anyway. If you get an FTPException, quit() will generally work.

You could do something like the below:

FTPClient ftp = null;
try {
    ftp = new FTPClient(...);
    // do ftp stuff
}
catch (FTPException ex) {
   // report
}
catch (IOException ex) {
   // report
}
finally {
   try {
       if (ftp != null)
          ftp.quit();
   }
   catch (IOException ex) {
       // report or ignore
   }
}

After some thinking -

ftp.quit(); throws IOException, so I have to try catch it if I don't want to throw it to the caller and it does not matter if I do it in finally or in first catch... Just to understand it 100% - I absolutely have to do ftp.quit() or the session will not be closed?
0 votes
by
Thanks a lot for your promt help!

BTW - the lib is SUPER fast! Keep up the good work! :wink:
0 votes
by (300 points)
After some thinking -

ftp.quit(); throws IOException, so I have to try catch it if I don't want to throw it to the caller and it does not matter if I do it in finally or in first catch... Just to understand it 100% - I absolutely have to do ftp.quit() or the session will not be closed?


I've wondered the same thing, and after reading this thread I'm going to put ftp.quit() in a 'finally' block and just ignore any exceptions.

Categories

...