To understand the block try/catch
it is necessary to understand the concept of exception. Do not be alarmed, it is quite common that this concept causes strangeness when you begin to study the object orientation paradigm.
Exception
In computer science, an exception is an object that defines an alternative flow to the normal execution of the program. This happens when some conditions in part of the program are not met, but can be treated, hence the term exception treatment. It is widely used when developing reusable libraries, in which the implemented business logic cannot be as rigid as it would be tied to an application only.
Imagine you have a function that performs the square root of a number. The code would be similar to this:
function sqrt ($number)
{
// Calcula a raiz quadrada
return $result;
}
However, considering only real numbers, the function will only work correctly if the input parameter is a non-negative value. Thus, if the parameter is negative, you must create an alternative flow to the program through an exception.
function sqrt ($number)
{
if ($number < 0)
{
throw new \Exception("$number must be a non-negative number");
}
// Calcula a raiz quadrada
return $result;
}
In this way, when trying to calculate the square root of a negative number, we would have:
> sqrt(-1);
Uncaught Exception: -1 must be a non-negative number ...
Exceptional treatment
With the block try/catch
you have the freedom to decide what the new program flow will be. In this example, let’s say that if the input value is negative, I want to calculate the square root of the same value, but positive, by emitting a Warning for the user. We could do something like:
$value = -4;
try {
$result = sqrt($value);
} catch (\Exception $e) {
log($e->getMessage());
$value *= -1; // Inverte o valor de $value
$result = sqrt($value);
warning("$value era negativo, então seu sinal foi alterado");
}
// Continuo com minha aplicação, onde $result = 2...
Being $e
an instance of Exception
, the method getMessage
return the defaced error message at the time of its shooting. In this case, it would be stored in the log from the system to message $number must be a non-negative number.
Your example
Using the library PDO
for connection to the database, we can see in documentation that the class constructor fires a type exception PDOException
if the connection fails. Therefore, making:
Collaboration of @bonifazio
try{
$pdo = new PDO(...);
$pdo->setAttribute(...);
...
}catch(PDOException $e){
// Omite a mensagem de erro para o cliente, só informando que houve um erro interno e salva o erro no log
log($e->getMessage());
http_response_code(500);
die("Ooops! Algo errado não está certo. Por favor, volte mais tarde.");
}
You ensure that in line $pdo->setAtributte
the variable $pdo
be an instance of PDO
with the connection active, because if the connection fails, the course of the program is changed to the block catch
. Without the use of blocks try/catch
You don’t have that guarantee. If the connection is not successful, the HTTP response code 500 is issued, informing an internal error, also showing the message to the user (considering that the connection to the database is trivial for the functioning of the system, which is what usually occurs).
You may ask yourself: but I just put one if
where I get the same guarantee. You can, but imagine that you are using a third party library in your application. If such an error happens, it is not good practice for you to edit source code directly by changing it to your application. If the library was well made, it will trigger the exception when situations like this occur and you capturing them can do the treatment without changing the code.
I found the explanation a little lacking, the
try
catch
creates a structure where the error will be treated as an exception and not an error (this exception can be saved in a log, for example, where only the developer will have access, and can correct the error), the code can continue the execution without any problem, thing that normally wouldn’t happen without the blocktry
catch
– MarceloBoni
Exception capturing syntax error? Are you sure about this?
– Woss
@Andersoncarloswoss might not get me to explain it right, syntax errors the compiler finds itself, but there are errors in libraries that uses the compiler does not find, and when this type of error occurs when using the Try catch it will fall in the catch.
– Daniel Saraiva