Search
Calendar
May 2025
S M T W T F S
« Apr    
 123
45678910
11121314151617
18192021222324
25262728293031
Archives

PostHeaderIcon (long tweet) A story of return in try/catch/finally

A short reminder: in a try/catch/finally section, the block in the finally is always executed. “Always” means “even if a return statement is reached in the try or catch“.

A short piece of code shows more than a long speech. The following JUnit test ends with no error:

package com.stepinfo.poc.cartography;

import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotSame;

/**
 * Created with IntelliJ IDEA 12 "Leda" CE
 * User: Jonathan LALOU
 * Date: 08/Apr/13
 * Time: 22:41
 */
public class TestTryCatchFinally {

    public static final String TRY = "try";
    public static final String CATCH = "catch";
    public static final String FINALLY = "finally";

    private String tryVersusFinally() {
        try {
            return TRY;
        } catch (Exception e) {
            return CATCH;
        } finally {
            return FINALLY;
        }
    }

    private String catchVersusFinally() {
        try {
            throw new RuntimeException();
        } catch (Exception e) {
            return CATCH;
        } finally {
            return FINALLY;
        }
    }

    @Test
    public void testTryFinally() {
        assertNotSame(TRY, tryVersusFinally());
        assertEquals(FINALLY, tryVersusFinally());
    }

    @Test
    public void testCatchFinally() {
        assertNotSame(CATCH, tryVersusFinally());
        assertEquals(FINALLY, catchVersusFinally());
    }
}

Leave a Reply