Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Monday, 14 June 2021

Php: uncaught exception handler

'set_exception_handler' function is used to catch any uncaught exceptions. Since the exception handler set by the method 'set_exception_handler' is called outside of the context where the actual error occurred, it is not possible to recover from the exception. It is mainly used to log the exception messages.

 

Step 1: Define a function that takes an exception as argument.

function my_exception_handler($e){
    echo "------------------------\n";
    echo "Uncaught exception handler\n";
    echo $e->getMessage();
    echo "\n------------------------\n";
}

 

Step 2: Set the function ‘my_exception_handler’ as uncaught exception handler.

set_exception_handler('my_exception_handler');

 

Find the below working application.

 

uncaught_exception_demo.php

#!/usr/bin/php

<?php 

function div($a, $b){
    if($b == 0){
        throw new LogicException('Division by zero');
    }
    return $a /$b;
}

function my_exception_handler($e){
    echo "------------------------\n";
    echo "Uncaught exception handler\n";
    echo $e->getMessage();
    echo "\n------------------------\n";
}

set_exception_handler('my_exception_handler');

div(10, 0);
?>

 

Output

$./uncaught_exception_demo.php 

------------------------
Uncaught exception handler
Division by zero
------------------------

 

 


Previous                                                    Next                                                    Home

Sunday, 13 June 2021

Php: finally block

The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. Finally block mainly used to perform clean-up operation like closing file streams, flushing the data etc.,

 

A try block must associate with at least one catch or finally block.

 

Example

try{
    div(10,0);
}catch(LogicException $e){
    echo "Exception occurred: ". $e->getMessage();
}finally{
    echo "\ni will execute always";
}

 

Find the below working application.

 

finally_block_demo.php

 

#!/usr/bin/php

<?php 

function div($a, $b){
    if($b == 0){
        throw new LogicException('Division by zero');
    }
    return $a /$b;
}

   try{
    div(10,0);
   }catch(LogicException $e){
       echo "Exception occurred: ". $e->getMessage();
   }finally{
    echo "\ni will execute always";
   }
?>

 

Output

$./finally_block_demo.php 

Exception occurred: Division by zero
i will execute always

 

  

Previous                                                    Next                                                    Home

Friday, 11 June 2021

Php: try and multiple catch statements

If the code in try block throws different kinds of exceptions, you can

Use multiple catch blocks different types of exceptions.

 

Example

try{
    div(10, '0');
}catch(LogicException $e){
    echo "LogicException Occurred : " . ($e -> getMessage()) . "\n";
}catch(RuntimeException $e){
    echo "RuntimeException Occurred : " . ($e -> getMessage()) . "\n";
}

 

Always catch more specific exceptions first followed by generic exceptions.

 

Find the below working example.

 

handle_multiple_exceptions.php

#!/usr/bin/php

<?php 

    function div($a, $b){
        if(!is_int($a) || !is_int($b)){
            throw new RuntimeException("This operation supported only for integers");
        }
        
        if($b == 0){
            throw new LogicException('Division by zero');
        }
        return $a /$b;
    }

    try{
        div(10, '0');
    }catch(LogicException $e){
        echo "LogicException Occurred : " . ($e -> getMessage()) . "\n";
    }catch(RuntimeException $e){
        echo "RuntimeException Occurred : " . ($e -> getMessage()) . "\n";
    }
    
?>

 

Output

$./handle_multiple_exceptions.php 

RuntimeException Occurred : This operation supported only for integers

 

 

 

 

Previous                                                    Next                                                    Home

Php: Handle Exceptions

Place the erroneous code in ‘try’ block, and handle the exceptions in catch block.

 

Example

try{
    div(10, 0);
}catch(LogicException $e){
    echo "Error Occurred : " . ($e -> getMessage()) . "\n";
}

 

Find the below working application.

 

try_catch_demo.php

#!/usr/bin/php

<?php 

    function div($a, $b){
        if($b == 0){
            throw new LogicException('Division by zero');
        }
        return $a /$b;
    }

    try{
        div(10, 0);
    }catch(LogicException $e){
            echo "Error Occurred : " . ($e -> getMessage()) . "\n";
    }
    
?>

Output

$./try_catch_demo.php 

Error Occurred : Division by zero


Previous                                                    Next                                                    Home

Tuesday, 8 June 2021

Php: How to throw an exception

‘throw’ keyword is used to throw an exception from a block of code.

 

Syntax

throw exception_object;

 

Example

throw new LogicException('Division by zero');

 

Following snippet calculate a/b, if b is 0, then it throws a LogicException.

function div($a, $b){
    if($b == 0){
        throw new LogicException('Division by zero');
    }
    return $a /$b;
}

 

Find the below working example.

 

throw_exception.php

#!/usr/bin/php

<?php 

    function div($a, $b){
        if($b == 0){
            throw new LogicException('Division by zero');
        }
        return $a /$b;
    }

   $result1 = div(10, 3);

   echo "\$result1: $result1\n";

   $result1 = div(10, 0);
    
?>

 

Output

$./throw_exception.php 

$result1: 3.3333333333333

Fatal error: Uncaught LogicException: Division by zero in /Users/krishna/eclipse-workspace/php_examples/exception_handling/throw_exception.php:7
Stack trace:
#0 /Users/krishna/php_examples/exception_handling/throw_exception.php(16): div(10, 0)
#1 {main}
  thrown in /Users/krishna/php_examples/exception_handling/throw_exception.php on line 7

 

 

 

 

 

 

 

Previous                                                    Next                                                    Home

Php: Exception handling

An exception represent an erroneous condition in the program.

 

Example

a.   you will get an exception when you try to perform some operation on unset variable.

b.   Accessing array element beyond its size throws an exception by Php

c.    When you are trying to read data from an url, but the service is down, then you will get service unavailable exception etc.,

 

Exception class is the base class for all the exceptions in Php.

Previous                                                    Next                                                    Home

Monday, 7 June 2021

Php: namespace: access entities using aliases

One of the advantage of Php namespaces is, you can create aliases to the existing entities.

 

Let’s see it with an example.

 

dynamic_logger.php

<?php

namespace DynamicLogger;

class Logger{
    public function log(){
        echo "I am dynamic logger\n";
    }
}

?>

 

logger.php

<?php

namespace CustomLogger;

class Logger{
    public function log(){
        echo "I am custom logger\n";
    }
}

?>

 

Let’s create alias names to Logger classes present in DynamicLogger and CustomLogger namespaces.

 

use DynamicLogger\Logger as MyDynamicLogger;

use CustomLogger\Logger as MyCustomLogger;

 

Find the below working application.

 

aliases.php

#!/usr/bin/php
<?php
    include 'logger.php';
    include 'dynamic_logger.php';

    use DynamicLogger\Logger as MyDynamicLogger;
    use CustomLogger\Logger as MyCustomLogger;

    $dyn_logger = new MyDynamicLogger();
    $cust_logger = new MyCustomLogger;

    $dyn_logger->log();
    $cust_logger->log();
    
?>

Output

$./aliases.php 
I am dynamic logger
I am custom logger

 

 

 

 

 

  

Previous                                                    Next                                                    Home

php: namespaces

Namespaces are used to

a.   Organize your code

b.   Solve naming conflict problems. For example, while developing an application, you may use some external libraries, there is a chance that multiple classes with same name. Using name spaces, we can avoid this name conflicts.

 

How to create a namespace?

Syntax

namespace namespace_name;

 

Let’s see it with an example.

 

arithmetic_utils_1.php

<?php

namespace nominal;

function area_of_circle($radius){
    return 3.14 * $radius;
}

?>

 

arithmetic_utils_2.php

<?php

namespace accurate;

function area_of_circle($radius){
    return 3.14285714 * $radius;
}

?>

As you see above snippets, I defined two namespaces.

a.   nominal

b.   accurate

 

Both the namespaces has ‘area_of_circle’ methods.

 

How to access the method defined in particular namespace?

Syntax

namespace_name\method_name(arguments);

 

Example

$area_of_circle_1 = nominal\area_of_circle($radius);

 

namespace_demo.php

#!/usr/bin/php

<?php
   include 'arithmetic_utils_1.php';
   include 'arithmetic_utils_2.php';

   $radius = 12.34;

   $area_of_circle_1 = nominal\area_of_circle($radius);
   $area_of_circle_2 = accurate\area_of_circle($radius);

   echo "for the radius $radius\n";
   echo "area_of_circle_1 : $area_of_circle_1\n";
   echo "area_of_circle_2 : $area_of_circle_2\n";

?>


Output

$./namespace_demo.php 

for the radius 12.34
area_of_circle_1 : 38.7476
area_of_circle_2 : 38.7828571076




 

 

Previous                                                    Next                                                    Home