Question:
I've been looking for some explanations on the subject, but I haven't found any that are simple and direct. My question is: What are the Try/Catch Blocks for and when should they be used?
Answer:
try/catch
is for exception handling, code handling that may not be fully met and generate some exception/error.
try
able to recover errors that may occur in the code provided in its block.
The catch
in turn handles the errors that occurred.
Example:
try {
//Esse código precisa de tratamento pois pode gerar alguma exceção
$x = 1;
if ($x === 1)
throw new \Exception('X não pode ser 1');
} catch (\Exception $e) {
var_dump($e->getMessage());
}
In addition, we also have a block called finally
(PHP 5.5 or higher), which provides instructions on what should be executed after try/catch
(usually releasing resources). If an exception is caught, finally
will be executed only after the instructions provided in catch
have finished. If no exception is thrown, finally
will be executed after the statements given in try
.
Example:
try {
//Esse código precisa de tratamento pois pode gerar alguma exceção
$variavel = AlgumaCoisa::pegarRecurso();
if ($variavel->executarAlgumaCoisa())
throw new \Exception('Erro: ' . $variavel->pegarErro());
} catch (\Exception $e) {
var_dump($e->getMessage());
} finally {
$variavel->liberarRecurso();
}
Finally, errors generated outside of a try/catch
can generate inconvenient messages for users using your system. Let's take an example:
//Nada antes
throw new Exception('teste');
//Nada depois
If the code above is executed, it will generate a very nice error message on the screen
//Fatal error: Uncaught exception 'Exception' with message 'teste' in ...