Jump to content

Why was "try" and "catch" introduced into PHP?


marcbraulio

Recommended Posts

a try catch block is in no way shape or form a loop.

It basically is an object oriented approach to error reporting, and really depends on your style of coding.

 

this:

 

$number = $_GET['number'];
if($number == 0)
{
    echo "number cannot be 0";
}
else
{
//proceed with code
}

 

does the exact same thing as this:

 

$number = $_GET['number'];
try
{
    if($number == 0)
    {
        throw new Exception("number cannot be 0");
    }
    //code down here will only be executed if the exception is not thrown
}
catch(Exception $e)
{
    echo $e->getMessage(); //outputs "number cannot be 0"
}

 

So, IMO if you are not programming in OO, you should stick to the if else blocks.

It makes more sense to use OO error_reporting if you code in OO, and procedural if you code in procedural.

But this is entirely up to you. I prefer to use try catch blocks simply because it allows me to check for multiple errors in one block and then proceed with the rest of the code, instead of having to use multiple elseif statements. Since a try block is broken out of after an Exception has been thrown and any code following the thrown Exception will not be executed, this allows for errors to be "tried" before the following code is executed.

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.