2011-10-06 143 views
0

我使用java连接到http服务器。一切皆好。当然,我收到了例外(SocketTimeoutException,ConnectException,IOException)。但我的问题是(例如)ConnectException发生时,应用程序停滞不前。我不能继续在程序的其他部分...我试过"return ..", System.exit(但我不想退出应用程序)。任何想法 ?如何退出捕捉异常

骨架PROG看起来是这样的:

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 ? 
} 

回答

0

如果添加finally块来你的尝试 - catch语句,你可以继续你的流量

try 
{ 

} 
catch{ 

} 
finally{ 

} 
+0

它总是最基本的东西卡住了。我看到了doc中的“finally”块,但没有写得很好。当然,它的工作。谢谢你们所有人去除我眼中的阴影。 – Zamboo

0

试图把finally块在你的代码捕获一个后。

0

你的问题不能没有更多地了解你的程序和环境来回答,但它可能是告知一个好主意用户关于连接失败,例如在一个对话框中显示“连接失败”。并且不要忘记关闭finally区块中的任何打开的连接。

0

你应该做的异常处理自己,如果连接失败或无效,则返回一个错误....

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

正如你所看到的,我确信,我的连接被关闭(finally块),这样我就不会在某个操作系统线程中留下打开的套接字。