简体   繁体   中英

When is a java exception thrown

Please see below pseudocode method. If the call to readUrls() throws an exception, doesn't that mean that closeConnection() will not be executed and program flow will return to the method that calls getdata() ?

Thanks

getdata() throws Exception
{
     setup();
     readUrls();
     closeConnection();
}

Your assumption is correct. To avoid this you can do something like this:

getdata() throws Exception
{
    setup();
    try { 
        readUrls();
    } finally {
        closeConnection();
    }
}

yes, if readUrls() throws an exception the flow will return to the method calling getdata() , where the same thing will happen, until:

  • there is a catch block, where the exception is handled
  • the exception bubbles up to the main method / to the run method of the thread.

When an exception is thrown, the current method call is interrupted and returns immediately. Use a try-catch-finally pattern for closing connections (with closeConnection() in the finally-statement))

It depends if you have not handled exception in readUrls() then Yes what you are saying is correct. That means you do not have try...catch in readUrls() method.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM