I'm using java to connect to http server. All is fine. Of course I catch exceptions ( SocketTimeoutException
, ConnectException
, IOException
). But my problem is when (for example) an ConnectException
occurs, the app stay stucked. I can't anymore continue in an other part of program... I tried "return ..", System.exit
(but I don't want to exit from application). Any idea ?
The skeleton prog looks like this:
boolean metod_to_check_http_server(){
try{
Create_connection(URL);
Set_Time_Out(3000);
open_HTTP_Connection();
Close_Connection();
return true; // All this part is fine...
}
catch (EXCEPTIONS)
{ // Here I know I have connection problem
// how could I return to main prog from here ?
// return false ? not work...
// System.exit(..); // too violent !
// so ?
}
尝试在捕获到一个代码之后将finally块放入您的代码中。
If you add finally block to your try - catch statement you can continue your flow
try
{
}
catch{
}
finally{
}
Your question cannot be answered without knowing more about your program and environment, but it might be a good idea to inform the user about the connection failure, for example in a dialog saying "Connection failed". And don't forget to close any open connections in a finally
block.
You should do exception handling yourself, and return a false if connection fails or is invalid....
boolean method_to_check_http_server(){
try{
Create_connection(URL);
Set_Time_Out(3000);
open_HTTP_Connection();
return true; // All this part is fine...
} catch (EXCEPTIONS) {
displayError();
return false;
} finally {
Close_Connection();
}
}
As you can see, I made sure that my connection is closed (in the finally block) so that I don't leave opened sockets running in some OS thread somewhere.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.