What are Try/Catch blocks?

Asked

Viewed 790 times

4

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

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

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

Perhaps some examples will help you to understand better

2 answers

12


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.

1

A "Try" block is called a "protected" block because, if a problem occurs with the commands inside the block, the execution will deviate to the corresponding "catch" blocks.

that is, if the code inside Try contains error (not logic error, but syntax error), it will fall into the catch where you can treat Exception.

  • 1

    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 block try catch

  • 4

    Exception capturing syntax error? Are you sure about this?

  • 1

    @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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.