Handle Exception in PHP

Handle Exception in PHP

Runtime Errors or Exception

Runtime Errors OR exceptions mainly occurs when there is an unexpected result while executing the programs. To handle Exception in PHP, we need to make some changes in the code itself to make sure that next time if such errors occur then the program itself, understands it, and operates on it effectively.

An exception was introduced in PHP5 and later it was redesign with many fixes in consecutive beta versions

Number of such improvisations are listed here

How To Handle Exception in PHP?

Let’s understand PHPs Exception handling –

Exception in PHP similar to other programming languages. The code which throws an exception can be surrounded by try block and one if any exception is thrown then it will be catched in catch block.

We can also define finally block. A finally block may also be specified after or instead of catch blocks. Code within the finally block will always be executed after the try and catch blocks, regardless of whether an exception has been thrown OR not.

Syntax-

<?php
try {
// code
} catch() {
// Handle Exception
} finally{
}

try – It contains code that uses exception. If exception did not trigger then code will execute as usual and if exception occured then it will be thrown.

catch – It contains code that will catch the exception thrown by the try statement. There are different types of exceptions. Depending on the exception we can write separate catch statement one by one. catch block accepts one parameter as exception object.

Exception class contains many methods that can be useful to get appropriate information needed.

finally – Finally statement is the default block of code which will be executed with exception is trown OR not.

Here is the list of Exceptions thrown when any such conditions arrises-

  • Bad Function Call Exception
  • Bad Method Call Exception
  • Domain Exception
  • Invalid Argument Exception
  • Length Exception
  • Logic Exception
  • Out Of Bounds Exception
  • Out Of Range Exception
  • Overflow Exception
  • Range Exception
  • Runtime Exception
  • Underflow Exception
  • Unexpected Value Exception

Let’s take an example of when bad Function Call Exception is thrown-

  • Bad Function Call Exception / BadFunctionCallException
<?php

/**
 * foo class
 */
class foo
{    
    /**
     * getName
     *
     * @return void
     */
    public function getName()
    {
        return ["class", "object", "final", "static"];
    }

    /**
     * __call
     *
     * @param  mixed $name
     * @param  mixed $argument
     * @return void
     */
    public function __call($name, $argument)
    {
        throw new BadMethodCallException("Function $name not found.");
    }
}
$objFoo = new foo;
try {
    echo $objFoo->executeId();
} catch (BadMethodCallException $e) {
    echo $e->getMessage();
}
OUTPUT:

Function executeId not found.

In the above example, we have seen that when we try to call a non existing class method then __call() method (which is a magic method in php) is executed. In this method, we can throw an exception with suitable message. This thrown message can be catched when such non-existing method is called using try{} catch(){} syntax.

  • Invalid Argument Exception / InvalidArgumentException
<?php

/**
 * foo class
 */

class foo
{
    /**
     * executeGetName
     *
     * @param  mixed $name
     * @return void
     */
    public function executeGetName($name)
    {
        if (!is_string($name)) {
            throw new InvalidArgumentException("passed argument can not be other that string.");
        }
        return ['class', 'object', 'final', ' static'];
    }
}

$objFoo = new foo;
try {
    echo $objFoo->executeGetName(123);
} catch (InvalidArgumentException $e) {
    echo $e->getmessage();
} catch (Exception $e) {
    echo $e->getmessage();
}
OUTPUT:

passed argument can not be other that string.

As the name itself says that, throw an exception when invalid argument is passed to the function. For example, if function is expecting string value and we are passing integer type then we can use this exception to throw the appropriate error.

  • Range Exception / RangeException
<?php
/**
 * foo class
 */
class foo
{
    /**
     * division
     *
     * @param  mixed $divident
     * @param  mixed $divisor
     * @return void
     */
    public function division($divident, $divisor)
    {
        if ($divisor <= 0 || $divident <= 0) {
            throw new RangeException("Invalid values are passed in the parameter. All the values must be greater than Zero.");
        }
        return $divident / $divisor;
    }
}

$objFoo = new foo;
try {
    echo $objFoo->division(123, 0);
} catch (RangeException $e) {
    echo $e->getMessage();
} catch (Exception $e) {
    echo $e->getMessage();
}
OUTPUT:

Invalid values are passed in the parameter. All the values must be greater than Zero.

In the above example, we have checked whether provided values are greater than zero. If either of those values is less than zero then we’ll throw an RangeException.

Conclusion-

There are so many ways to Handle Exception in PHP and we can create our custom class to write by extending parent class Exception. This way we can customize the things as per our need.

To Handle Exception in PHP, we need to first understand the basic difference between errors and exception and once idea gets clear then we can use the try catch to greater extend.