try-finally block continue for loop

╄→гoц情女王★ 提交于 2020-01-25 13:03:40

问题


I'm writing a loop that ignored the Exception and it works well.

    for (; flag; ) {
        try {
            //do something ignore exception.
            Runnable r = queue.pollFirst();
            r.run();
        } catch (Exception ignored) {
            // ignored.
        }
    }

But my question is: If I don't catch RuntimeException and force continue loop in finally block, what will happen to the Exception and returned value?

Example:

    for (int i = 0; i < 10; i++) {
        try {
            System.out.println(i);

            throw new RuntimeException();
        } finally {
            //what will happen to the exception if continue loop?
            continue;
        }
    }

回答1:


They will be ignored as the finally block has the final word.




回答2:


Runtime Exception will be ignored because there is no catch block to access/use (e.g. for logging purpose) thrown object of java.lang.RuntimeException. finally block does not have any access to Exception object thrown by try block. Its better to have catch block to get more information.




回答3:


Not sure why you would want to catch a RuntimeException because by the time you even try catching it, it's too late therefore your continue will never hit.



来源:https://stackoverflow.com/questions/37007725/try-finally-block-continue-for-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!