Last active
December 18, 2015 22:48
-
-
Save marxjohnson/5856890 to your computer and use it in GitHub Desktop.
PHP finally keyword
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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(); | |
} |
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();
}
}
Thanks Tim, good example.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What's the difference? Under what circumstances would the first example not run
some_code()
?