Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return, inside or outside Try / catch?

Tags:

php

try-catch

In the below code, the IDE alerts me about "Missing return statement" in the last bracket. Which leads me to ask here if the return inside the try{} is ok or should be outside it.

Thanks a lot.

public function getFileNamesFromKeywords( array $ids, $format ) {
    try {
      if(self::$dbLink) {
        $ids = implode(',',$ids);
        $query = 'SELECT d.id, d.wfid, d.docid , k.keyword, k.value'.
          'FROM keywords k'.
          'INNER JOIN documents d '.
          'ON k.document_id = d.id'.
          'WHERE k.document_id IN ('.$ids.')';
        $results = self::$dbLink->query($query);

        if( $results === false ) {
          throw new Exception('Ocurrió un error al consultar a la DB.', 500);
        }
        $results = $results->fetchAll(PDO::FETCH_ASSOC);
        $filenames = $this->buildFileNames( $results, $ids, $format );
      }
      else {
        throw new Exception('No hay una conexión establecida con la DB.', 500);
      }
      return $filenames;
    }
    catch(Exception $e) {
      $this->error = 'Error al intentar conectar con la BD: ' . $e->getMessage();
    }
  } //<----- Missing return statement
like image 576
JorgeeFG Avatar asked Sep 23 '13 15:09

JorgeeFG


People also ask

Should return be inside try catch?

No, it's not a bad practice. Putting return where it makes sense improves readability and maintainability and makes your code simpler to understand. You shouldn't care as finally block will get executed if a return statement is encountered. Show activity on this post.

Where should I return in try and catch?

In a try-catch-finally block that has return statements, only the value from the finally block will be returned. When returning reference types, be aware of any updates being done on them in the finally block that could end up in unwanted results.

What should I return after try catch?

All code after it will be perfectly reachable. And finally returns nothing at all. It is just a block of code that is executed unaware of if there was an exception or not.

Can I return inside a catch?

Yes, we can write a return statement of the method in catch and finally block. There is a situation where a method will have a return type and we can return some value at any part of the method based on the conditions.


4 Answers

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.

like image 130
Joni Avatar answered Oct 11 '22 13:10

Joni


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.

like image 17
Brian Kinyua Avatar answered Oct 11 '22 13:10

Brian Kinyua


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;
}
like image 1
Gareth Luckett Avatar answered Oct 11 '22 14:10

Gareth Luckett


I believe that generaly speaking proper place for return statement is inside of finally part

function doSomenthing() {
    $result = SomeDefaultValue;
    try {
        // code
        $result = ResultValueIfEverythingIsOK;
    }
    catch {
        // error handler code
    }
    finally {
        return ($result);
    }
}

You can get unhandled exception inside your error handler code and then you don't have guarantee that return statement will be executed unless it is inside finally part.

like image 1
ivo.tisljar Avatar answered Oct 11 '22 12:10

ivo.tisljar