Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the `finally` keyword for in PHP?

Tags:

Consider these two examples

<?php
function throw_exception() {
    // Arbitrary code here
    throw new Exception('Hello, Joe!');
}

function some_code() {
    // Arbitrary code here
}

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

some_code();

// More arbitrary code
?>

and

<?php
function throw_exception() {
    // Arbitrary code here
    throw new Exception('Hello, Joe!');
}

function some_code() {
    // Arbitrary code here
}

try {
    throw_exception();
} catch (Exception $e) {
    echo $e->getMessage();
} finally {
    some_code();
}

// More arbitrary code
?>

What's the difference? Is there a situation where the first example wouldn't execute some_code(), but the second would? Am I missing the point entirely?

like image 868
marxjohnson Avatar asked Jun 25 '13 08:06

marxjohnson


People also ask

What is the use of finally keyword?

The finally keyword is used to create a block of code that follows a try block. A finally block of code always executes, whether or not an exception has occurred. Using a finally block allows you to run any cleanup-type statements that you just wish to execute, despite what happens within the protected code.

What is a Finally block PHP?

The finally is an optional block of the try… catch statement. The finally block always executes after the try or catch block. In this case, if an exception occurs while reading the file, the execution jumps to the catch block to handle it and then the finally block executes to close the file.

When and where is the finally keyword used?

The finally keyword is used to execute code (used with exceptions - try.. catch statements) no matter if there is an exception or not.

What is a final class PHP?

Definition of PHP Final Class. PHP final class is a class which prevents overriding a method of the child classes just by the final prefix with the definition. It means that if we are defining a method with the final prefix then it is going to prevent overriding the method.


1 Answers

If you catch Exception (any exception) the two code samples are equivalent. But if you only handle some specific exception type in your class block and another kind of exception occurs, then some_code(); will only be executed if you have a finally block.

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

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

but:

try {
    throw_exception();
} catch (ExceptionTypeA $e) {
    echo $e->getMessage();
} finally {
    some_code(); // Will be execute even if throw_exception throws an ExceptionTypeB
}
like image 164
Simon Avatar answered Sep 21 '22 11:09

Simon