What are the Try / Catch blocks?


I would like to know what the try...catch blocks are.

I would like more information in Portuguese, because in English I did not understand much, only that it would be a kind of if...else .

  • What are these try...catch blocks?
  • When do I have to use them?
  • Always (should) use them when I have a SQL query?

Perhaps some examples help you understand better

asked by anonymous 07.03.2017 / 19:20

2 answers


To understand the block try/catch it is necessary to understand the concept of exception. Do not be alarmed, it is quite common for this concept to be awkward as you begin to study the object-oriented paradigm.


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 that can be handled, so the expression handling exceptions. It is widely used when developing reusable libraries, where the business logic implemented can not be as rigid as it would be stuck to an application only.

Imagine that you have a function that performs the square root of a number. The code would look like 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. This way, if the parameter is negative, you should create an alternative flow for 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 ...

Exception handling

With 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 compute the square root of the same value, but positive, by issuing a warning to the user. We could do something like:

$value = -4;

try {
    $result = sqrt($value);
} catch (\Exception $e) {
    $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 getMessage method will return the error message defined at the time of its firing. In this case, the $ number must be a non-negative number message would be stored in the log

Your example

Using the PDO library for the database connection, we can see the documentation that the class constructor throws an exception of type PDOException if the connection fails. So by doing:

Collaboration of @bonipazio

  $pdo = new PDO(...);
}catch(PDOException $e){
  // Omite a mensagem de erro para o cliente, só informando que houve um erro interno e salva o erro no log
  die("Ooops! Algo errado não está certo. Por favor, volte mais tarde.");

You guarantee that on%> with% is variable $pdo->setAtributte is an instance of $pdo with the active connection, because if the connection fails, the program path changes to the PDO block. Without the catch blocks you do not have this 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 with the bank is trivial for the operation of the system, which is what usually occurs).

You may wonder: but I just put a try/catch there that I get the same warranty. You can, but imagine that you are using a third-party library in your application. If such an error occurs, it is not a good practice for you to edit the source code directly by changing it for your application. If the library was well made, it will trigger the exception when situations occur and you can capture them without changing the code.

07.03.2017 / 20:00

A "try" block is called a "protected" block because, in case of a problem with the commands within the block, execution will be diverted to the corresponding "catch" blocks.

That is, if the code that is inside the try contains an error (not a logic and syntax error), it will fall into the catch where you can handle the exception.

07.03.2017 / 19:25