What is the finally used in PHP 5.5?

10

PHP 5.5 has implemented a feature (which I've heard of in other languages) called finally , in handling exceptions (along with try/catch )

We have the following example:

set_error_handler(function ($errno, $errstr, $errfile, $errline ) {

    throw new ErrorException($errstr, 0, $errno, $errfile, $errline); 

});

try{

    $b = (new stdClass)->non_exists; // gera um erro de propósito

} catch(Exception $e) {

 echo  $e->getMessage(), PHP_EOL; // imprime a mensagem da captura da exceção

} finally {

   echo 'acabou!'; // imprime "acabou" (indepentende de entrar no catch ou não
}

In practice, what could be useful to use finally ? (because I do not understand why it runs even when it does not fall within catch )

    
asked by anonymous 26.01.2015 / 15:42

2 answers

9

Essentially it is to ensure that the flow of that block is always executed. Even if an exception occurs in the block started by try , the finally block will be executed before exiting the function and start dropping the function call stack.

In general it is used to terminate allocated resources, for example closing a file.

There may be a question of what the difference is to catch which also runs when there is an exception. The difference is that catch is only executed when there is the exception. finally is executed with or without exception. The program execution flow goes from try to finally always, either because try quit normally, or because it raised an exception. catch is a conditional execution block (by throwing an exception), finally is required execution.

Remembering that throwing an exception will enforce both the catch and finally blocks, but any code that comes after this try-catch-finally block will not run .

You may get an impression of little use of it because of examples that do nothing useful effectively.

Documentation .

Good generic example:

    $recurso = abrir_recurso();
    try {
        $resultado = use_rercurso($rercurso);
    } finally {
        libere_rercurso($rercurso); //acontecendo ou não uma exceção, o recurso será fechado
    }
    return $resultado;

Actual example taken blog :

function addRecord($record, $db) {
    try {
      $db->lock($record->table);
      $db->prepare($record->sql);
      $db->exec($record->params);
    } catch(Exception $e) {
        $db->rollback($record);
        if (!write_log($e->getMessage(), $e->getTraceAsString())) {
            throw new Exception('Unable to write to error log.');
        }
    } finally {
        $db->unlock($record->table);
    }
    return true;
}

The example is bad because it captures Exception and launches again but the general idea is this. Suggested reading . It's not the same language but it works the same way.

    
26.01.2015 / 15:48
4

Try = > It is the command block you want to execute

Catch = > It is the command block to execute in case of an error (Exception). You Can Treat Multiple% of%. exceptions will only be executed when an exception occurs.

finally = > Since Catch is the block that executes only when an exception occurs, catch will always execute, regardless of error. A good utility of finally is to close the connection to the database.

    
26.01.2015 / 16:24