Question:
I've been looking for some explanations on the subject, but I haven't found any that were simple and straightforward. My question is: What are the Try/Catch Blocks for and when should they be used?
Answer:
The try/catch
is for handling exceptions, handling codes that may not be fully met and generate some exception/error.
The try
able to recover errors that might occur in the code given in your block.
The catch
in turn, handles the errors that happened.
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 provide instructions of what should be executed after the try/catch
(usually releasing resources). If an exception is caught, the finally
will be executed only after finishing the instructions given in catch
. If no exceptions are thrown, the finally
will be executed after the statements given in the 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 a try/catch
can generate inconvenient messages for users who use 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 ...