Skip to content

Instantly share code, notes, and snippets.

@marxjohnson
Last active December 18, 2015 22:48
Show Gist options
  • Save marxjohnson/5856890 to your computer and use it in GitHub Desktop.
Save marxjohnson/5856890 to your computer and use it in GitHub Desktop.
PHP finally keyword
<?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();
<?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();
}
@marxjohnson
Copy link
Author

What's the difference? Under what circumstances would the first example not run some_code()?

@timhunt
Copy link

timhunt commented Jun 25, 2013

No difference in your example, but what if you are in a function, and you don't acutally want to catch the exception, but you need to guarantee to clean up before exiting the function. Without finally you have to duplicate code:

function do_thing() {
    allocate_resource(); // e.g. open a file.
    try {
        may_throw_exception();
        clean_up(); // e.g. close file
    } catch (Exception $e) {
        clean_up(); // DUPLICATE CODE!!!
        throw $e;
    }
}

With finally, you can do

function do_thing() {
    allocate_resource();
    try {
        may_throw_exception();
    } finally {
        clean_up();
    }
}

@marxjohnson
Copy link
Author

Thanks Tim, good example.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment