finally关键字

版权声明:有些文章写的很随意,那是仅作为个人记录的文章,建议直接关掉,多看一秒亏一秒 https://blog.csdn.net/qq_36523667/article/details/82983301

怎么突然提起这个了,是因为看见了Okhttp的源码才感觉奇怪。

Response response;
boolean releaseConnection = true;
try {
    response = realChain.proceed(request, streamAllocation, null, null);
    releaseConnection = false;
} catch (RouteException e) {
    if (!recover(e.getLastConnectException(), streamAllocation, false, request)) {
        throw e.getFirstConnectException();
    }
    releaseConnection = false;
    continue;
} catch (IOException e) {
    boolean requestSendStarted = !(e instanceof ConnectionShutdownException);
    if (!recover(e, streamAllocation, requestSendStarted, request)) throw e;
    releaseConnection = false;
    continue;
} finally {
    if (releaseConnection) {
        streamAllocation.streamFailed(null);
        streamAllocation.release();
    }
}

于是我测试了下

public class Test {
    public static void main(String args[]) {
        for (int i = 0; i < 2; i ++) {
            try {
                throw new Exception();
            } catch(Exception e) {
                continue;
            } finally {
                System.out.println("lll");
            }
        }
    }
}

会输出2次

public class Test {
    public static void main(String args[]) {
        for (int i = 0; i < 2; i ++) {
            try {
                throw new Exception();
            } catch(Exception e) {
                return;
            } finally {
                System.out.println("lll");
            }
        }
    }
}

会输出1次

得出结论如下:
不管catch中有什么return,continue,break,在终结前,都要先执行finally里的代码。这是编译器行为。

猜你喜欢

转载自blog.csdn.net/qq_36523667/article/details/82983301
今日推荐