Why should I use exception handling in php?

I have been programming PHP for a long time, but not much PHP 5 ... I have known for some time about exception handling in PHP 5, but I never looked at it. After a quick Google, it seems pointless to use exception handling - I don't see the benefits of using it only with some if () {} statements and maybe my own error handling class or something else.

There must be many good reasons for using it (I think ?!), otherwise it would not be put into the language (maybe). Can someone tell me about some good benefits associated with using just any if statements or a switch statement or something else?

+7
source share
9 answers

Exceptions allow you to distinguish between different types of errors, and are also great for routing. For example...

class Application { public function run() { try { // Start her up!! } catch (Exception $e) { // If Ajax request, send back status and message if ($this->getRequest()->isAjax()) { return Application_Json::encode(array( 'status' => 'error', 'msg' => $e->getMessage()); } // ...otherwise, just throw error throw $e; } } } 

An abandoned exception can be handled by a special error handler.

Since PHP is a freely typed language, you may need to make sure that only strings are passed as arguments to the class method. For example...

 class StringsOnly { public function onlyPassStringToThisMethod($string) { if (!is_string($string)) { throw new InvalidArgumentException('$string is definitely not a string'); } // Cool string manipulation... return $this; } } 

... or if you need to handle different types of exceptions differently.

 class DifferentExceptionsForDifferentFolks { public function catchMeIfYouCan() { try { $this->flyForFree(); } catch (CantFlyForFreeException $e) { $this->alertAuthorities(); return 'Sorry, you can\'t fly for free dude. It just don\'t work that way!'; } catch (DbException $e) { // Get DB debug info $this->logDbDebugInfo(); return 'Could not access database. What did you mess up this time?'; } catch (Exception $e) { $this->logMiscException($e); return 'I catch all exceptions for which you did not account!'; } } } 

If you use transactions in something like Zend Framework:

 class CreditCardController extends Zend_Controller_Action { public function buyforgirlfriendAction() { try { $this->getDb()->beginTransaction(); $this->insertGift($giftName, $giftPrice, $giftWowFactor); $this->getDb()->commit(); } catch (Exception $e) { // Error encountered, rollback changes $this->getDb()->rollBack(); // Re-throw exception, allow ErrorController forward throw $e; } } } 
+6
source

Exception handling: if the condition against Exception is not specific to PHP, but gives a good perspective. Personally, Exception and try / catch are implemented in languages ​​to ensure good behavior among developers who would usually not be as attentive to error checking / handling.

If you are sure that your if / else if / else captures all the scripts, not cool.

Here is an overview of the Benefits of Exceptions - Java - At some point there is a piece of code that has a lot if / else and the following passage:

There are so many errors in detecting, reporting, and returning here that the original seven lines of code get lost in a mess. Worse, the logical flow of code was also lost, which makes it difficult to determine the correctness of the code: is the file really closed if the function does not allocate enough memory? Even harder to make sure the code continues to do the right thing when you change the method three months after writing it. Many programmers solve this problem simply by ignoring it - errors are reported when their programs fail.

So, in the end, it comes down to personal preference. If you want the code to be readable and can be used by other people, it is usually better suited and provides the best behavior.

+3
source

If you are implementing an object-oriented methodology, exceptions are convenient for handling errors. It is convenient to report errors through an exception between objects. Exceptions are really useful if you go with a layered design.

If you are not coding in an object oriented way, then exceptions are not required.

+2
source

We use exception handling if we are not sure about the results of the code. We put this piece of code in a try block and catch this error in a catch block. Please check this link for more information.

+2
source

In general, there are two good reasons for using exception handling:

  • Now you can always know where the exception will occur - something unexpected may occur. If you use a global exception handler, you can make sure that no matter what goes wrong, your program has the ability to recover. Likewise, a particularly sensitive piece of code (for example, something that I / O does) can have all kinds of errors that can only be detected at runtime, and you want to catch any possible unforeseen situation. There may be some problems during testing; how if the server outside your control is down? This may never be tested before it happens (although good testing will include this). This is a really important reason.

  • Performance

    . As a rule, exceptions are implemented so that everything is fast until nothing happens. Exceptions are caught after they appear. This means that the if statement must be evaluated in advance if something goes wrong, in which case the overhead is very low. If you do not use exceptions, you will be forced to add a lot of "if" to your code. While this is usually not a big problem, it can lead to a critical, performance-critical application. This is especially true because incorrect branch prediction in the CPU can lead to pipeline flow.

+1
source

I understand that an Exception is thrown after trigger_error (); and you can also send additional information to this exception = is it better to debug?

I'm not sure, but I think that he

Example:

db class {connect () function {mysql_Connect ("lolcalhost", "root", "pass :)") or trigger_error ("Test"); }} try {} catch (db Strike>

0
source

One of the main reasons for having an exception framework is that if the code ever comes to the point where it cannot act, it has the ability to tell the surrounding context that something went wrong. This means that if I have a Foo class that should have $fooInstance->setBarHandler($barHandler) , which is called before $fooInstance->doFoo(); may succeed, the class may provide a message to a larger context, rather than fail and return FALSE . In addition, he lets the context say, β€œYes, it’s broken. Well, now I can tell the user / logs / something else that something happened and I can decide if I need to continue interrupting.”

0
source
  • Exceptions can provide much more data than simple -1 or false .
  • Exceptions can perform advanced error handling. Keep in mind that try .. catch blocks can be nested, and there can be more than one catch block in a try .. catch catch .
  • Exceptions force you to handle errors. When you do not use them, you do something like:

     function doSomething($a, $b, $c) { ... if ($a < $b && $b > $c) { return -1; // error } ... } $d = doSomething($x, $y, $z); if ($d === -1) { die('Fatal error!'); } 

    And everything is fine until you forget to check whether the function returned an error. But what happens if you forget to check it out? This is actually a fairly common problem.

  • Exceptions make program flow more natural.

0
source

Exceptions are hard to use in the right context, especially in php. Personally, I use exceptions when these 3 things happen:

Resource failure exception . You can exclude it, maybe when your program has run out of memory. for example in php when running a script that exceeds 30 seconds. Although you can use this in .ini

Client code error exceptions . For example, when you try to connect to the database with the wrong credentials or cancel a file that is not on the server. Or when the database server is down and not responding, you can throw an exception.

Programmer error exception . These are errors that occur due to your own encoding problems. It can also be used when you are not sure about the results that your code will give you. for example, when divided by 0.

0
source

All Articles