Finally Clause in PHP

PHP has supported the finally clause.Finally will executed after a try block no matter what is your condition. if the try block threw an exception or not.

<?php

try 
{
    print "Start executing try block BEFORE exception." . PHP_EOL;
    throw new Exception("This is my exception");
    print "Executing try block AFTER exception thrown." . PHP_EOL;
} 
catch (Exception $e) 
{
    print "Executing the catch block." . PHP_EOL;
} 
finally 
{
    print "Executing 'finally' block." . PHP_EOL;
}

print "Executing code after finally." . PHP_EOL;

Start executing try block BEFORE exception.
Executing the catch block.
Executing 'finally' block.
Executing code after finally.

so finally is executed even if exception occurred. we can understand this with the below two examples.

try {
    throw_exception();
} catch (ExceptionTypeA $e) {
    echo $e->getMessage();
}

example(); // Will not execute if throw_exception throws an ExceptionTypeB

But this will execute.

try {
    throw_exception();
} catch (ExceptionTypeA $e) {
    echo $e->getMessage();
} finally {
    some_code(); // Will be execute even if throw_exception throws an ExceptionTypeB
}

As you can see the finally block is still executed, even though something went wrong within our exception handling.

No comments:

Post a Comment

Download the eBook of react js for beginners

ReactJS basically is an open-source JavaScript library which is used for building user interfaces specifically for single page applications...

Popular