Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should last statement be `return` in and non void return types method?

Tags:

java

return

Should last statement be return in and non void return types method? But this is still working.

public String test()
{
    try
    {
        // Do my work
        return "myValue";
    }
    finally
    {
        System.out.println("I'm in Finally");
    }
}

I'm bit lack of knowledge to understand how this work. Could someone explain me.

like image 319
someone Avatar asked Apr 13 '26 10:04

someone


1 Answers

There is no problem with this code, because every possible path through it inevitably leads to a return statement*. It does not have to be the last statement textually, as long as it is the last statement logically (Java compiler is smart enough to figure out if it's so, and give you an error if there are paths through your code that do not return a value or throw an exception). The fact that there will be code executing after hitting the return (i.e. your finally block) does not change anything: as far as the compiler is concerned, your function has provided a return value before exiting the function.

* In fact, there is only one path through your function's code, and it terminates at the return statement.

like image 88
Sergey Kalinichenko Avatar answered Apr 15 '26 00:04

Sergey Kalinichenko