How and when to use exceptions in PHP?

Asked

Viewed 5,374 times

7

In PHP, most native functions return a boolean false, whole 0 or NULL if some type 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 ends up leaving the job of validating the function to the developer, who decides how (or if) to treat the same.

On the other hand, if all the functions went off exceptions the developer would have much more work to use try/catch in all functions that he used to not break the code.

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

  • Have you read this? http://answall.com/questions/21767/por-que-devemos-evitar-retornar-c%C3%b3digos-de-error

  • 1

    I believe that we should always seek to use it as a way to prevent and identify errors. Personally I use whenever I use O.O. in my code, as well as in database queries.

2 answers

6


When to use exceptions?

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

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

When you should not use exceptions?

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

However, a method that opens a file and performs some processing could launch an exception once 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 treatment of exceptions with Try/Catch:

function fileContent($file)
{
  try {
        return file_get_contents($file);
  } 
  catch (Exception e) {
        echo $e->getMessage(), "\n";
  }
}
  • You know that the first example creates a race condition?

  • For demonstration purposes I believe that the example is valid. =)

  • In what way, @mustache ?

  • 1

    @Sunstreaker it is but it would be good to make this clear because many people copy these things thinking that everything is ok.

  • 1

    @Tassoevangelist Because you check if the file exists, then you will read the content and it may no longer exist.

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 shall be used to treat events that change the normal flow running a PHP script. We usually assume that these events are logical or runtime errors (Runtime), but are also useful in assertion failures such as user or programmer’s own data entry validation errors.

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

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

Browser other questions tagged

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