关于try-catch的问题

时间:2011-06-07 16:28:59

标签: java android exception-handling try-catch

我在理解try{} catch(Exception e){...}的工作方式时遇到了问题!

假设我有以下内容:

try
{
    while(true)
    {
        coord = (Coordinate)is.readObject();//reading data from an input stream
    }
}
catch(Exception e)
{
    try{
        is.close();
        socket.close();
    }
    catch(Exception e1)
    {
        e1.printStackTrace();
    }
}

第2节

    try
    {
        is.close();
        db.close();
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }

假设我的while()循环因is流异常而抛出错误。

这会让我走出无限循环,把我扔进第一个catch(){............} 块。

我的问题如下:

抛出异常后,退出循环while()并转到

catch(){ 
}

我的程序会继续执行并转到第2部分吗?只要异常被抓住了?或者一切都在第一个catch()

结束

4 个答案:

答案 0 :(得分:3)

只要您的catch子句中没有抛出异常,您的程序将在catch(或finally)子句之后继续执行。如果需要从catch子句重新抛出异常,请使用throw;或抛出新的例外(ex)。不要使用throw ex,因为这会改变异常的堆栈跟踪属性。

答案 1 :(得分:3)

我想你想在第一次捕获[finally]之后使用catch (Exception e)关闭你的溪流:

try {
    // Do foo with is and db
} catch (Exception e) {
    // Do bar for exception handling
} finally {
    try {
        is.close();
        db.close();
    } catch (Exception e2) {
      // gah!
    }
}

答案 2 :(得分:2)

捕获异常后,在try / catch块之后继续执行。在这种情况下,这是你的第2部分。

未捕获的异常将终止线程,这可能会终止进程。

答案 3 :(得分:1)

是的,你是对的。它将移至第2节

如果您希望第2节绑定发生,无论是否生成任何异常,您可能希望将它们包含在finally块中。

try {
    // Do foo with is and db
} 
catch (Exception e) {
    // Do bar for exception handling
}  

// Bound to execute irrespective of exception generated or not ....
finally {
      try {
          is.close();
          db.close();
        }
     catch (Exception e2) {
      // Exception description ....
    }
}
相关问题