How and when to use exceptions in PHP?

6

In PHP, most native functions return a boolean false , integer 0 or NULL if some kind of inconsistency is found in the value passed to it. Example:

$exemplo1 = explode("","tente me explodir"); // false
//ou
$exemplo2 = count(NULL) // 0

This type of solution eventually leaves the job of validating the function for the developer, who decides how (or if) it should treat the same.

On the other hand, if all functions fired exceptions the developer would have much more work having to use try/catch on all functions that he used to not pop the code.

So, if neither PHP uses exceptions often, when should the developer use them? Is it preferable to use the same method used by the language, that is, return false in the functions and treat them when necessary? Or do you always fire a exception when the input is not what you expected?

    
asked by Kazzkiq 19.06.2014 в 23:18
source

2 answers

6

When should you use exceptions?

You use an exception to indicate an exceptional condition, that is, something that prevents a method from fulfilling its purpose and should not have occurred at that level.

For example, you might have a method that saves changes to a record in a database. If for some reason this can not be done (for example, some error occurs in the database), then you can throw an exception to indicate the failure.

When should you not use exceptions?

Consider a method that checks for the existence of a file, this should probably not throw an exception if the file does not exist, since the purpose of the method was to check for existence.

However, a method that opens a file and performs some processing might throw an exception, since the file is expected to exist.

function fileContent($file)
{
  if (!file_exists($file))
   throw new Exception("O arquivo não pode ser encontrado", 1);

  return file_get_contents($file);  
}

Or with exception handling with Try/Catch :

function fileContent($file)
{
  try {
        return file_get_contents($file);
  } 
  catch (Exception e) {
        echo $e->getMessage(), "\n";
  }
}
    
answered by 19.06.2014 / 23:33
source
3
  

Exception handling is the process of responding to the occurrence, during computation, of exceptions - anomalous or exceptional events requiring special processing - often changing the normal flow of program execution. It is provided by specialized programming language constructs or computer hardware mechanisms. 1

Exceptions should be used to handle events that change the normal flow of running a PHP script. We usually assume that these events are logical or runtime errors, but they are also useful in assertion failures, such as user data entry validation errors or the scheduler itself.

However, it should be remembered that exceptions were introduced only in PHP 5, while the functions quoted in your question are from earlier versions. Some old classes that you will find will also use the return of false or null on some methods to flag errors.

There are many advantages to using exceptions, but I personally believe debugging with them is far superior. Once an exception is thrown exactly where an error occurs, the stack trace will provide you with a precise string of calls on which lines of code the exception passed. A false return of a complex method will not tell you where execution failed, unless you debug line by line. It is not uncommon for me to have to handle thrown exceptions show more than 15 methods executed.

    
answered by 19.06.2014 в 23:32