What is the difference between PHP’s "Exception"?

Asked

Viewed 742 times

6

Has several Exception defined in PHP, as ErrorException PDOException Error ArithmeticError, etc....

  • But what’s the point of having so many exceptions?
  • There’s a difference between using one and the other?
  • 1

    The main difference is semantics. If programmers understood this, it would help. The exception is the most poorly used programming feature today. Most have not the slightest notion of how an exception works even. Always a horror show. But it works, right, so it seems to be right.

  • 2

    When the person actually understands the difference of casting the correct exception, the person will probably understand the difference of capturing the correct exception and never make another catch (Exception ex) {, except in the rare case when it is the right one.

  • Can you help me by giving at least a hint of when it’s right? Even something for me to read or something, so I can get it straight, please. Thank you!

  • 3

    If I can, read everything, you can get tired, but if you finish everything and still make the wrong exception, you can sell hot dogs on the corner :D http://answall.com/search?tabvotes&q=user%3a101%20[exce%C3%A7%C3%A3o]. If you still have specific unanswered questions, you can open questions.

4 answers

7


The purpose is for you to be able to capture a specific exception.

All Exceptions in PHP derive from the class Exception. When you capture Exception you are capturing any exception that occurs while executing the code.

Example:

 try{

      throw new InvalidArgumentException('Teste');

  } catch (Exception $e) {
          echo $e->getMessage();
  }

In this case, it is advantageous to do so if you really want to capture any exception that occurs in that section of Try/catch.

Why use a specific exception?

But it is not always the case. Often, you need to know exactly what the exception was to perform a certain error treatment. For example, if one function invokes a mathematical error exception and another points out that the argument is not numerical, you may want to just use the exception either inform the error of the calculation to inform a log to the user, whereas the error of the argument you may want to leave itlo as fatal error (because in PHP, when throwing an exception without captured, you generate a fatal error).

Capturing specific exceptions

One point we should touch on is that Exceptions are varied because the problems are varied. So you use a specific Exception for each problem.

Consider for example a function where you have an argument that should be one array and that array must have 2 entries. In this case, you will have to use an exception to indicate that it is not an array and another, to indicate invalid size.

Example:

  function tem_que_ser_array_com_dois_itens($array) {
       if (! is_array($array)) {
            throw new \InvalidArgumentException('O argumento não é array');
       }

       if (count($array) !== 2) {
            throw new \LengthException("Tamanho do array é inválido. Deve ser apenas 2 itens');
       }
  }

So, to work with the possible exceptions released by this function, you can specify which exception you want to "capture" in the catch if you didn’t want to capture any one.

Example:

    try {

           tem_que_ser_um_array_com_dois_itens(1);
     } catch (InvalidArgumentException $e) {
          $e->getMessage();
     }

In the above example, only InvalidArgumentException is captured, because we want to treat an exception only because the argument is not valid. If the size is invalid, in the above example, the exception will be converted by PHP to a Fatal error, since it was not "captured/handled".

If you used Exception in the catch above, you would capture any exception generated by the function - because all exception classes derive from Exception, in PHP versions prior to version 7.

Multiple catches of exceptions

But still this behavior may not be what you want. Then, you may wish to treat both invalid and invalid argument exceptions. How could you resolve this?

The solution is to use multiple catch. PHP allows this.

Example:

 try {
       tem_que_ser_array_com_dois_itens([1]);
  } catch (InvalidArgumentException $e) {

       echo 'Por favor, coloque um array';
  } catch (LengthException $e) {
       echo 'Seu array tá com tamanho errado';
  }

Simply answering your questions:

But what’s the point of having so many exceptions?

Each exception represents an exception that can occur during the code. Exceptions may be invalid sizes, unexpected types, runtime errors. That is why there needs to be a specific exception for each case, because if you used throw new Exception for everything, you wouldn’t know how to treat a specific exception and it would give you a lot of headache.

In addition to using PHP’s own exceptions, you can also create your own.

Example:

   class InvalidImageExtension extends \InvalidArgumentException {}

   if (! in_array($extensao, ['png', 'jpg', 'bmp']) {
         throw new InvalidImageExtension('Extensão inválida');
   }

There’s a difference between using one and the other?

Like I said, it takes an exception to identify a specific problem. That is, it would not be organized to throw the same exception to treat invalid argument and to treat an error while opening a file. Each case is a case.

Example that wouldn’t be cool:

try {

      if (is_array($array) {
           // Poderia ser UnexpectedValueException 
           // Ou InvalidArgumentException, se isso for argumento de uma função
           throw new Exception('Não é um array');
      }

      if (file_exists($file)) {
          // Poderia ser RunTimeException (erro no tempo de excecução)
          throw new Exception('Arquivo não existe');
      }
} catch (Exception $e) {

      // Se seu chefe pedir para você enviar um e-mail
      // Toda vez que não conseguir abrir um arquivo
      // Como você ia tratar isso? Fazendo IF?
     // Não seria melhor lançar e capturar uma exceção só para o arquivo não existente?

}

Show which Exception your boom function

I don’t know if you use PHPDocumentor, but it is always good to notice that some libraries specify exceptions that can be released in their code through comments like @throws. So, if you wish, you can capture the specific exception instead of trying to guess.

Example:

 /**
 *
 * @param boolean $motor_ligado
 * @param string $modelo
 * @throws ProblemaNoMotorException
 * @throws VeiculoNaoVoadorException
 */
 function voar($motor_ligado = true, $modelo = 'aviao') 
 {
     if ($motor_ligado === false) {
          throw new ProblemaNoMotorException('Motor não está ligado');
     }

     if (! in_array($modelo, ['aviao', 'helicoptero']) {
        throw new VeiculoNaoVoadorException('Esse veículo não serve');
        // Ou UnexpectedValueException, por exemplo
     }
 }

What is rethrow?

I’ve seen this term used in some frameworks, the rethrow. That is to say "re-launch". Sometimes you want to do a specific operation on catch, but you still need the Fatal Error generated by that exception.

In this case, you can cast the same exception after capturing it on catch.

See a useful example where I need to finalize a request on a customer’s webservice. If an error occurs, in addition to launching the exception, I need to register it in a log.

Then I can capture her, log her and launch her again:

 try {

    $db->finalizarNoWebserviceDoCliente();


 } catch (ServerException $e) {

    $db->logs()->registrarLog($e->getMessage());

    // Você lança a exceção novamente aqui
    throw $e;
 }
  • The example is good to show the mechanism, but it’s good to make it clear that capturing programming error and telling the programmer to fix the code doesn’t make much sense in real code. Programming error is not captured in real code, only in same example.

  • @Bigown I was going to comment on the issue of rethrow just for that. Because the times I needed to capture an exception, or was to register a log for me to resolve later or was to send an email and then cast the same exception for the user

  • 1

    Good work, worthy of +10 :D

2

Yes, there is difference. When you use Exception in a Try catch any kind of error will fall in the catch. If you specify another as Pdoexception you are setting a specific error type to be caught by the catch. I use Laravel in development and when I want to capture errors from querys I use:

try{
  //meu código
} catch (\Illuminate\Database\QueryException $e) {

    return $e->getMessages();
}

0

It all depends on the exception you want to grab.

By EX:

try {
    $PDO = new PDO('...');
}
catch( PDOException $Exception ) {
    echo 'Conexão à base de dados não foi bem sucedida';
}

Here you want to grab only this Exception, letting others throw their natural, in catch you can put up a 'Plan B' connection of another kind if it fails. Notice that in this case it will only be useful to grab this (PDOException)

This is useful for example within the catch send a custom message depending on the exception, or do another action, until you define a new path of your program depending on the exception you want to take in a try catch.

0

I recently had a different experience, I realized that even using Try/catch with Exception was popping a fatal error on the screen. I managed to resolve by making another catch to capture the Throwable error.

    try{        
    } catch(\Throwable $e) {
        ...
    } catch(\Exception $e) {
        ...
    }

Browser other questions tagged

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