【问题标题】:How to quit from a catch exception如何从捕获异常中退出
【发布时间】:2011-10-06 08:12:24
【问题描述】:

我正在使用 java 连接到 http 服务器。一切皆好。当然我会捕获异常(SocketTimeoutExceptionConnectExceptionIOException)。但我的问题是当(例如)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 ?
}

【问题讨论】:

    标签: java exception try-catch


    【解决方案1】:

    如果你在 try - catch 语句中添加 finally 块,你可以继续你的流程

    try
    {
    
    }
    catch{
    
    }
    finally{
    
    }
    

    【讨论】:

    • 卡住的总是最基本的东西。我在 doc 中看到了“finally”块,但写得不好。当然,它有效。所以感谢大家去除我眼睛上的阴影。
    【解决方案2】:

    尝试在你的代码中添加 finally 块在 catch 之后。

    【讨论】:

      【解决方案3】:

      如果不了解您的程序和环境的更多信息,您的问题将无法回答,但最好将连接失败通知用户,例如在显示“连接失败”的对话框中。并且不要忘记关闭 finally 块中的任何打开的连接。

      【讨论】:

        【解决方案4】:

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

        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 块中),这样我就不会让打开的套接字在某个 OS 线程中运行。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-10-07
          • 1970-01-01
          • 1970-01-01
          • 2011-06-27
          • 2016-02-09
          • 1970-01-01
          • 2013-03-23
          • 2014-09-11
          相关资源
          最近更新 更多