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.

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.