Return, inside or outside Try / catch?

If an exception is thrown and caught, what will the function return?

You should have a return statement in the catch block, or after the try-catch block. Having a return statement in the try-block only is not enough.


The message you are being given is just a warning, as your code may not return anything. The best option to do as add a return to your catch if you want to stop the warning.

Just add the return before the closing brace.

catch(Exception $e) {
    $this->error = 'Error al intentar conectar con la BD: ' . $e->getMessage();
    return null;
}

if you place a return statement inside a function at any location then it's expected that the function has to return something and since you have placed the return statement inside a try-catch block ,when the IDE evaluates thw code it notices that you don't have a return statement for when your try fails that is in the catch.

I would recommended creating a $response variable initialized to false at the top of the function then assign the $filenames to it then after the try-catch block return the $response.

function getFilenames(){
    $response = false;

    try{
        //your code
        $response = $filenames;
    }catch{

    }

    return $response;
}

By doing so you ensure that the function always returns something either the results you need or false.

Tags:

Php

Try Catch