Why do some tutorials (online and books) lead you astray?

I decided to start a new thread for the other thread was getting quite lengthy and thought it would be best to start a new one. Anyways, when I first started learning PHP I went to using books for I thought they would be “better” than online tutorials. I was sure wrong, for the author used try…catch to report errors when using PDO. I just found out that isn’t the best policy -

[i]However, in general, no dedicated treatment for PDO exceptions is ever needed. In short, to have PDO errors properly reported:

Set PDO in exception mode.
Do not use try…catch to report errors.
Configure PHP for proper error reporting
on a live site set display_errors=off and log_errors=on
on a development site, you may want to set display_errors=on
of course, error_reporting has to be set to E_ALL in both cases
As a result, you will be always notified of all database errors without a single line of extra code! [/i]

The link to that good article is https://phpdelusions.net/pdo (I think it might had been posted here before, but at the time I never paid attention to it.)

Programming can be bad enough, but having people who are supposedly “experts” showing people who are new to PHP (or any programming language) wrong techniques or procedures can be frustrating to say the least. I used to say to people learning PHP to use a book for online tutorials can be horrible; however, I think I need to revise this to “be careful in selecting a tutorial” by doing some background checking on the tutorial itself. However, this can be potentially frustrating for a new person learning to code. :’(

HTH someone - John

Books go out of date quickly, from the time of writing to publishing, to buying. That process takes time and coding standards can change quickly.

I use try catch statements, and will continue to do so. I also write programs in several other languages and that is how exceptions are handled across the board. Just because php wants to go against the norm, which is one reason many developers despise the language, doesn’t mean I will handle it that way.

It just gets me when you are taught one way from a reputable source and a few months later someone else comes along and says you’re doing wrong. It’s frustrating for you know it can’t be that wrong (if at all) even if they have a point. Maybe that’s a better way of writing it? (English was never my favorite subject ;D)

If my memory serves me right when I took a C+ course in college a long time ago the language used try…catch (or something similar for I can’t remember exactly). I thought try…catch handled exceptions (I think at that that time they called it error blocking or something like that and I do see that phrase every once in while still thrown around). I can see where some people don’t like PHP, while I don’t despise PHP I’ll just live with it for it’s something I’m starting to get a grasp of. The language that I really like actionscript 3 (Flash), but that has really fallen out of favor and I haven’t touched in awhile now. It was easy to write games and apps with graphics and animations. Though I’m tempted in going back to it and just hooking it up with php to save the data and what have you.

I use try catch statements, and will continue to do so.

Please don’t.

In PHP this is completely unnecessary and will fill your app with a lot of unnecessary code. Until as recent as 3 months ago or so I did the same thing until someone that knew more than me schooled me. I spent the next two days updating the project I was working on removing the try/catch’s.

In regards to the PDO exceptions where the try/catch is being used, there are many more exceptions other than PDO exceptions. Plenty more not being said here…

Your friend here is set_exception_handler.
http://php.net/manual/en/function.set-exception-handler.php

I wont go full school in depth here. This is summed up in get rid of the the try/catch blocks and use set_exception_handler.

One place to still use the try/catch would be on a duplicate entry to catch that specific error and provide a relevant error message.

Example:
[php] catch (PDOException $e)
{
if ($e->getCode() == ‘23000’)
{
$error[] = “That whatever already exists.”;
$error[] = “Duplicate Whatever are not allowed.”;
show_form_errors($error);
}
}[/php]

Set Exception Handler Code Example:

Main config:
[php]// Set user-defined exception handler function (config/functions.php)
set_exception_handler(“custom_exception”);[/php]

[php]//----------------------------------------------------------------------------
// User-defined exception handler function
//----------------------------------------------------------------------------

function custom_exception($e)
{
global $stmt, $mysql_datetime, $errorlog_path, $email_to, $email_from;

$error_msg = $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine();

echo '<div class="error_custom"><H4>Fatal Error!</H4></div>';

if (DEBUG == 1)
    {
    echo '<div class="error_custom"><H1>DEBUGGING IS ON !!!</H1></div>';
    echo '<div class="error_custom">Error Message:<br>' . $error_msg . '</div>';

    echo '<div class="error_custom">SQL Statement:<br>';
    echo '' . $stmt->debugDumpParams() . '';
    echo '</div>';

    echo '<div class="error_custom">Stack Trace:<br>';
    foreach ($e->getTrace() as $trace)
        {
        echo $trace['file'] . ' Line #' . $trace['line'] . '<br>';
        }
    echo '</div>';
    } //DEBUG == 1

if (EMAIL_ERROR == 1)
    {
    echo '<div class="error_custom"><H4>Admin has been notified</H4></div>';
    error_log("ERROR: $error_msg\n", 1, "$email_to", "From: $email_from");
    } //EMAIL_ERROR == 1

// Write error to log
if (LOG_ERROR == 1)
    {
    echo '<div class="error_custom"><H4>Error has been logged</H4></div>';
    error_log("$mysql_datetime|$error_msg\r\n", 3, "$errorlog_path");
    } //LOG_ERROR == 1

die;
}[/php]

Coding standards and best practices are highly opinionated. In professional environments these may differ (greatly) from team to team. Most programming languages in themselves are quite unopiniated, meaning you can basically write your app however you see fit. This is one of the big reasons I like using frameworks as they do come with a set of opinionated “rules” (conventions/standards). It helps both individual, freelance, small and large teams follow the same thoughtset when building applications instead of everyone building their own set of rules/conventions (reality).

Expert isn’t a protected title. I think that many people misinterpret the feeling of mastering solving problems that you get when you’re programming with some achieved skill level (expert!). This leads to many people jumping on the “I should write a tutorial/book” wagon much too early. It’s quite understandable though - of course you want to share your new found love/passion with others. But you’re in no way in a position to actually do so (properly).

In addition you of course have the problem of technology moving in such a high pace. A tutorial is almost out of date (no longer conforming to standards) when it’s done. A book with practical examples is even worse in that aspect. That’s why I strongly believe books work mostly for more abstract topics. I much prefer reading “clean code” than some PHP book with lots of (outdated) code snippets.

If it’s for your own personal projects then sure. If it’s for anyone else then please don’t. If nothing else then at least for the fact that flash is now being removed from existence (finally). And that’s coming from someone who used to love flash, though as you said, that’s quite a few years ago.

If you’re into games and similar I suggest you take a look at the modern game engines that’s out there. Unity is free to use and offer a very good experience where you can use either C# or JavaScript (UnityScript) for your game spesific logic

Most programming languages in themselves are quite unopiniated, meaning you can basically write your app however you see fit.

That has always been my peeve with Php. Too many ways to do the same exact thing. If you recall, we did that thing to see how many ways we could output the standard “Hello World!”. There is upwards of a hundred ways.

I recently started dabbling in Python. To my joy and amazement, for the most part there is only one way to do things. I also started playing around in Java. That seems to be pretty tight as well.

First, I like try catches and in your own opinion they are still useful in order to direct the flow of the program.

I find it interesting that PHP can institute a catchall for exception handling, yet you still have to micromanage code bases to prevent injections. Ever try to do a javascript or html injection on an ASP site? You can’t. It natively determines that something isn’t right and handles it for you. Yet, PHP still requires the developer to go in-depth to remove possibly malicious inputs through validation.

EVERY high level and low level (excluding languages like assembly) use try catch. They are useful to handle the flow of the program in a way that you want.

For instance, if I want SQL errors going to a DBA and code issues going to developers, I can easily see where they are going and how it is being handled. It goes along with code readability.

Now, I have used the function in question on a very large application. It worked wonderfully for logging issues.

It really comes down to the right tool for the right job. You gave a good example for try/catch when you want to handle particular exceptions in a particular way. Try/Catch and set_exception_handler are just tools in the tool box.

As you can see, I use set_exception_handler to log and notify me of problems to display detailed errors for debugging, logging errors, and emailing me when the production site has a problem. In my world I am always the entire team so set_exception_handler is the best tool for me to use.

Sponsor our Newsletter | Privacy Policy | Terms of Service