<p>What are the pros/cons of doing either way.  Is there One Right Way(tm) ?</p>

[{'answer_id': 60631, 'author': 'Nick Stinemates', 'author_id': 4960, 'author_profile': 'https://Stackoverflow.com/users/4960', 'pm_score': 2, 'selected': False, 'text': '<p>It depends on the situation. I tend to use Exceptions when I am writing business logic/application internals, and trigger_error for Validator\'s and things of that sort.</p>\n\n<p>The pro\'s of using Exceptions at the logic level is to allow your application to do in case of such an error. You allow the application to chose instead of having the business logic know how to present the error.</p>\n\n<p>The pro\'s of using trigger_error for Validator\'s and things of that nature are, say,</p>\n\n<p>\n\n<pre><code>try {\n    $user-&gt;login();\n}  catch (AuthenticationFailureException $e) {\n    set_error_handler("my_login_form_handler");\n    trigger_error("User could not be logged in. Please check username and password and try again!");\n} catch (PersistenceException $pe) { // database unavailable\n    set_error_handler("my_login_form_handler"); \n    trigger_error("Internal system error. Please contact the administrator.");\n}\n</code></pre>\n\n<p>where my_login_form_handler pretties up the string and places the element in a visible area above the login form.</p>\n'}, {'answer_id': 60813, 'author': 'reefnet_alex', 'author_id': 2745, 'author_profile': 'https://Stackoverflow.com/users/2745', 'pm_score': 3, 'selected': False, 'text': "<p>I love the idea of using exceptions, but I often have third party libraries involved, and then if they don't use exceptions you end up with 3-4 different approaches to the problem! Zend uses exceptions. CakePHP uses a custom error handler, and most PEAR libraries use the PEAR::Error object. </p>\n\n<p>I which there WAS one true way in this regard. The custom error handlers route is probably the most flexible in this situation. Exceptions are a great idea though if you're either only using your own code, or using libraries that use them. </p>\n\n<p>Unfortunately in the PHP world we're still suffering from the refusal to die of PHP4, so things like exceptions, while they may represent best practise have been incredibly slow to catch on while everyone is still writing things to be able to work in both 4 and 5. Hopefully this debacle is now ending, though by the time it does, we'll have tensions between 6 and 5 instead... </p>\n\n<p>/me holds head in hands...</p>\n"}, {'answer_id': 76111, 'author': 'farzad', 'author_id': 9394, 'author_profile': 'https://Stackoverflow.com/users/9394', 'pm_score': 2, 'selected': False, 'text': '<p>The idea of exception is elegant and makes the error handling process so smooth. but this only applies when you have appropriate exception classes and in team development, one more important thing is "standard" exceptions. so if you plan to use exceptions, you\'d better first standardize your exception types, or the better choice is to use exceptions from some popular framework. one other thing that applies to PHP (where you can write your code object orienter combined with structural code), is that if you are writing your whole application using classes. If you are writing object oriented, then exceptions are better for sure. after all I think your error handling process will be much smoother with exception than trigger_error and stuff.</p>\n'}, {'answer_id': 82207, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>Obviously, there\'s no "One Right Way", but there\'s a multitude of opinions on this one. ;)</p>\n\n<p>Personally i use trigger_error for things the exceptions cannot do, namely notices and warnings (i.e. stuff you want to get logged, but not stop the flow of the application in the same way that errors/exceptions do (even if you catch them at some level)).</p>\n\n<p>I also mostly use exceptions for conditions that are assumed to be non-recoverable (to the caller of the method in which the exception occurs), i.e. serious errors. I don\'t use exceptions as an alternative to returning a value with the same meaning, if that\'s possible in a non-convoluted way. For example, if I create a lookup method, I usually return a null value if it didn\'t find whatever it was looking for instead of throwing an EntityNotFoundException (or equivalent).</p>\n\n<p>So my rule of thumb is this:</p>\n\n<ul>\n<li>As long as not finding something is a reasonable result, I find it much easier returning and checking for null-values (or some other default value) than handling it using a try-catch-clause.</li>\n<li>If, on the other hand, not finding it is a serious error that\'s not within the scope of the caller to recover from, I\'d still throw an exception.</li>\n</ul>\n\n<p>The reason for throwing exceptions in the latter case (as opposed to triggering errors), is that exceptions are much more expressive, given that you use properly named Exception subclasses. I find that using PHP\'s Standard Library\'s exceptions is a good starting point when deciding what exceptions to use: <a href="http://www.php.net/~helly/php/ext/spl/classException.html" rel="nofollow noreferrer">http://www.php.net/~helly/php/ext/spl/classException.html</a></p>\n\n<p>You might want to extend them to get more semantically correct exceptions for your particular case, however.</p>\n'}, {'answer_id': 170546, 'author': 'Andrei Rînea', 'author_id': 1796, 'author_profile': 'https://Stackoverflow.com/users/1796', 'pm_score': 1, 'selected': False, 'text': '<p>The Exceptions are the modern and robust way of signaling an error condition / an exceptional situation. Use them :)</p>\n'}, {'answer_id': 525113, 'author': 'Luke P M', 'author_id': 53608, 'author_profile': 'https://Stackoverflow.com/users/53608', 'pm_score': 3, 'selected': False, 'text': '<p>You should use exceptions in "Exceptional circumstances", that is when you call a method doFoo() you should expect it to perform, if for some reason doFoo is unable to do it\'s job then it should raise an exception.</p>\n\n<p>A lot of old php code would take the approach of returning false or null when a failure has occured, but this makes things hard to debug, exceptions make this debugging much easier. </p>\n\n<p>For example say you had a method called getDogFood() which returned an array of DogFood objects, if you called this method and it returns null when something goes wrong how will your calling code be able to tell whether null was returned because there was an error or there is just no dog food available?</p>\n\n<p>Regarding dealing with legacy code libraries that use php\'s inbuilt error logging, you can override the error logging with the set_error_handler() function, which you could use to then rethrow a generic Exception.</p>\n\n<p>Now that you have all of your code throwing detailed exceptions, you are free to decide what to do with them, in some parts of your code you may wish to catch them and try alternative methods or you can log them using your own logging functions which might log to a database, file, email - whichever you prefer. In short - Exceptions are more flexible .</p>\n'}, {'answer_id': 1129157, 'author': 'shadowhand', 'author_id': 49146, 'author_profile': 'https://Stackoverflow.com/users/49146', 'pm_score': 4, 'selected': False, 'text': '<p>If you want to use exceptions instead of errors for your entire application, you can do it with <a href="http://php.net/ErrorException" rel="noreferrer">ErrorException</a> and a custom error handler (see the ErrorException page for a sample error handler). The only downside to this method is that non-fatal errors will still throw exceptions, which are always fatal unless caught. Basically, even an <code>E_NOTICE</code> will halt your entire application if your <a href="http://php.net/error_reporting" rel="noreferrer">error_reporting</a> settings do not suppress them.</p>\n\n<p>In my opinion, there are several benefits to using ErrorException:</p>\n\n<ol>\n<li>A custom exception handler will let you display nice messages, even for errors, using <a href="http://php.net/set_exception_handler" rel="noreferrer">set_exception_handler</a>.</li>\n<li>It does not disrupt existing code in any way... <a href="http://php.net/trigger_error" rel="noreferrer">trigger_error</a> and other error functions will still work normally.</li>\n<li>It makes it really hard to ignore stupid coding mistakes that trigger <code>E_NOTICE</code>s and <code>E_WARNING</code>s.</li>\n<li><p>You can use <code>try</code>/<code>catch</code> to wrap code that may generate a PHP error (not just exceptions), which is a nice way to avoid using the <code>@</code> error suppression hack:</p>\n\n<pre><code>try {\n    $foo = $_GET[\'foo\'];\n} catch (ErrorException $e) {\n    $foo = NULL;\n}\n</code></pre></li>\n<li><p>You can wrap your entire script in a single <code>try</code>/<code>catch</code> block if you want to display a friendly message to your users when any uncaught error happens. (Do this carefully, because only uncaught errors and exceptions are logged.)</p></li>\n</ol>\n'}, {'answer_id': 13334532, 'author': 'unity100', 'author_id': 1792090, 'author_profile': 'https://Stackoverflow.com/users/1792090', 'pm_score': -1, 'selected': False, 'text': "<p><em><strong>Using exceptions are not a good idea in the era of 3rd party application integration</em></strong>. </p>\n\n<p>Because, the moment you try to integrate your app with something else, or someone else's app with yours, your entire application will come to a halt the moment a class in some 3rd party plugin throws an exception. Even if you have full fledged error handling, logging implemented in your own app, someone's random object in a 3rd party plugin will throw an exception, and your entire application will stop right there. </p>\n\n<p><em><strong>EVEN if you have the means in your application to make up for the error of that library you are using</em></strong>....  </p>\n\n<p>A case in example may be a 3rd party social login library which throws an exception because the social login provider returned an error, and kills your entire app unnecessarily - hybridauth, by the way. So, There you have an entire app, and there you have a library bringing in added functionality for you - in this case, social login - and even though you have a lot of fallback stuff in the case a provider does not authenticate (your own login system, plus like 20 or so other social login providers), your ENTIRE application will come to a grinding halt. And you will end up having to change the 3rd party library to work around these issues, and the point of using a 3rd party library to speed up development will be lost. </p>\n\n<p>This is a serious design flaw in regard to philosophy of handling errors in PHP. Lets face it - under the other end of most of applications developed today, there is a user. Be it an intranet user, be it a user over internet, be it a sysadmin, it does not matter - there is generally a user.</p>\n\n<p>And, having an application die on your face without there being anything you can do at that point other than to go back to a previous page and have a shot in the dark regarding what you are trying to do, as a user, is bad, bad practice from development side. Not to mention, an internal error which only the developers should know due to many reasons (from usability to security) being thrown on the face of a user. </p>\n\n<p>As a result, im going to have to just let go of a particular 3rd party library (hybridauth in this case) and not use it in my application, solely for that reason. Despite the fact that hybridauth is a very good library, and apparently a lot of good effort have been spent on it, with a phletora of capabilities. </p>\n\n<p>Therefore, you should refrain from using exceptions in your code. EVEN if the code you are doing right now, is the top level code that will run your application, and not a library, it is possible that you may want to include all or part of your code in other projects, or have to integrate parts or entirety of it with other code of yours or 3rd party code. And if you used exceptions, you will end up with the same situation - entire applications/integrations dying in your face even if you have proper means to handle whatever issue a piece of code provides.</p>\n"}, {'answer_id': 13655714, 'author': 'Tivie', 'author_id': 295342, 'author_profile': 'https://Stackoverflow.com/users/295342', 'pm_score': 2, 'selected': False, 'text': '<h2>Intro</h2>\n\n<p>In my personal experience, as a general rule, I prefer to use Exceptions in my code instead of trigger_error. This is mainly because using Exceptions is more flexible than triggering errors. And, IMHO, this is also beneficial not only for myself as for the 3rd party developer.</p>\n\n<ol>\n<li>I can extend the Exception class (or use exception codes) to explicitly differentiate the states of my library. This helps me and 3rd party developers in handling and debugging the code. <strong>This also exposes where and why it can fail</strong> without the need for source code browsing.</li>\n<li>I can effectively halt the execution of my Library without halting the execution of the script.</li>\n<li>The 3rd party developer can chain my Exceptions (in PHP > 5.3.*) Very useful for debugging and might be handy in handling situations where my library can fail due to disparate reasons.</li>\n</ol>\n\n<p>And I can do all this without imposing how he should handle my library failures. (ie: creating complex error handling functions). He can use a try catch block or just use an generic exception handler</p>\n\n<p><em><strong>Note:</em></strong></p>\n\n<p>Some of these points, in essence, are also valid for trigger_error, just a bit more complex to implement. Try catch blocks are really easy to use and very code friendly.</p>\n\n<hr>\n\n<h2>Example</h2>\n\n<p>I think this is an example might illustrate my point of view:</p>\n\n<pre><code>class HTMLParser {\n    protected $doc;\n    protected $source = null;\n    public $parsedHtml;\n    protected $parseErrors = array();\n    public function __construct($doc) {\n        if (!$doc instanceof DOMDocument) {\n            // My Object is unusable without a valid DOMDOcument object\n            // so I throw a CriticalException\n            throw new CriticalException("Could not create Object Foo. You must pass a valid DOMDOcument object as parameter in the constructor");\n        }\n        $this-&gt;doc = $doc;\n    }\n\n    public function setSource($source) {\n        if (!is_string($source)) {\n            // I expect $source to be a string but was passed something else so I throw an exception\n            throw new InvalidArgumentException("I expected a string but got " . gettype($source) . " instead");\n        }\n        $this-&gt;source = trim($source);\n        return $this;\n    }\n\n    public function parse() {\n        if (is_null($this-&gt;source) || $this-&gt;source == \'\') {\n            throw new EmptyStringException("Source is empty");\n        }\n        libxml_use_internal_errors(true);\n        $this-&gt;doc-&gt;loadHTML($this-&gt;source);\n        $this-&gt;parsedHtml = $this-&gt;doc-&gt;saveHTML();\n        $errors = libxml_get_errors();\n        if (count($errors) &gt; 0) {\n            $this-&gt;parseErrors = $errors;\n            throw new HtmlParsingException($errors[0]-&gt;message,$errors[0]-&gt;code,null,\n                $errors[0]-&gt;level,$errors[0]-&gt;column,$errors[0]-&gt;file,$errors[0]-&gt;line);\n        }\n        return $this;\n    }\n\n    public function getParseErrors() {\n        return $this-&gt;parseErrors;\n    }\n\n    public function getDOMObj() {\n        return clone $this-&gt;doc;\n    }\n}\n</code></pre>\n\n<hr>\n\n<h2>Explanation</h2>\n\n<p>In the <strong>constructor</strong> I throw a <em><code>CriticalException</code></em> if the param passed is not of type <em><code>DOMDocument</code></em> because without it my library will not work at all. </p>\n\n<p>(Note: I could simply write <code>__construct(DOMDocument $doc)</code> but this is just an example).</p>\n\n<p>In <strong><code>setsource()</code></strong> method I throw a <em><code>InvalidArgumentException</code></em> if the param passed is something other than a string. I prefer to halt the library execution here because <strong>source property</strong> is an essential property of my class and an invalid value will propagate the error throughout my library.</p>\n\n<p>The <strong><code>parse()</code></strong> method is usually the last method invoked in the cycle. Even though I throw a <em><code>XmlParsingException</code></em> if libXML finds a malformed document, the parsing is completed first and the results usable (to an extent).</p>\n\n<hr>\n\n<h2>Handling the example library</h2>\n\n<p>Here\'s an example how to handle this made up library:</p>\n\n<pre><code>$source = file_get_contents(\'http://www.somehost.com/some_page.html\');\ntry {\n    $parser = new HTMLParser(new DOMDocument());\n    $parser-&gt;setSource($source)\n           -&gt;parse();\n} catch (CriticalException $e) {\n    // Library failed miserably, no recover is possible for it.\n    // In this case, it\'s prorably my fault because I didn\'t pass\n    // a DOMDocument object.\n    print \'Sorry. I made a mistake. Please send me feedback!\';\n} catch (InvalidArgumentException $e) {\n    // the source passed is not a string, again probably my fault.\n    // But I have a working parser object. \n    // Maybe I can try again by typecasting the argument to string\n    var_dump($parser);\n} catch (EmptyStringException $e) {\n    // The source string was empty. Maybe there was an error\n    // retrieving the HTML? Maybe the remote server is down?\n    // Maybe the website does not exist anymore? In this case,\n    // it isn\'t my fault it failed. Maybe I can use a cached\n    // version?\n    var_dump($parser);\n} catch (HtmlParsingException $e) {\n    // The html suplied is malformed. I got it from the interwebs\n    // so it\'s not my fault. I can use $e or getParseErrors() \n    // to see if the html (and DOM Object) is usable\n    // I also have a full functioning HTMLParser Object and can\n    // retrieve a "loaded" functioning DOMDocument Object\n    var_dump($parser-&gt;getParseErrors());\n    var_dump($parser-&gt;getDOMObj());\n}\n$var = \'this will print wether an exception was previously thrown or not\';\nprint $var;\n</code></pre>\n\n<p>You can take this further and nest try catch blocks, chain exceptions, run selective code following a determined exception chain path, selective logging, etc...</p>\n\n<p>As a side note, using Exceptions does not mean that the PROGRAM execution will halt, it just means that the code depending of my object will be bypassed. It\'s up to me or the 3rd party developer to do with it as he pleases.</p>\n'}]
['https://Stackoverflow.com/questions/60607', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']