开发者

question about try-catch

开发者 https://www.devze.com 2023-03-11 20:11 出处:网络
I have a problem understanding how the try{} catch(Exception e){...} works! Let\'s say I have the following:

I have a problem understanding how the try{} catch(Exception e){...} works!

Let's say I have the following:

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

Section 2

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

Let's say my while() loop throws an error because of an exception of is stream.

This will get me out of the infinite loop and throw me in the first catch(){............} block.

My question is the following:

After throwing an exception, getting out of the loop while() an开发者_运维问答d reaching to

catch(){ 
}

Will my program continue his execution and move on to section 2? As long as the exception was caught? Or everything ends in the first catch()?


I think you want to use finally after your first catch [catch (Exception e)] to close your streams:

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


As long as no exceptions are thrown in your catch clause, your program will continue execution after your catch (or finally) clause. If you need to rethrow the exception from the catch clause, use throw; or throw new Exception(ex). Do not use throw ex, as this will alter the stack trace property of your exception.


After the exception is caught, execution continues after the try/catch block. In this case, that's your section 2.

An uncaught exception will terminate the thread, which might terminate the process.


Yes, you are right. It will move to Section 2.

If you want your Section 2 bound to happen, irrespective of any exception generated, you might want to enclose them in a finally block.

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 ....
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号