Java Language Exceptions and exception handling Return statements in try catch block


Although it's bad practice, it's possible to add multiple return statements in a exception handling block:

 public static int returnTest(int number){
        if(number%2 == 0) throw new Exception("Exception thrown");
        else return x;
    catch(Exception e){
        return 3;
        return 7;

This method will always return 7 since the finally block associated with the try/catch block is executed before anything is returned. Now, as finally has return 7;, this value supersedes the try/catch return values.

If the catch block returns a primitive value and that primitive value is subsequently changed in the finally block, the value returned in the catch block will be returned and the changes from the finally block will be ignored.

The example below will print "0", not "1".

public class FinallyExample {

    public static void main(String[] args) {
        int n = returnTest(4);

    public static int returnTest(int number) {
        int returnNumber = 0; 
        try {
            if (number % 2 == 0)
                throw new Exception("Exception thrown");
                return returnNumber;
        } catch (Exception e) {
            return returnNumber;
        } finally {
            returnNumber = 1;