note 114207 added to language.exceptions
| From: | php at marcuspope dot com | Date: | Fri, 24 Jan 2014 17:43:00 +0000 |
| Subject: | note 114207 added to language.exceptions | ||
| Groups: | php.notes php.notes | ||
| Request: | Send a blank email to php-notes+get-198330@lists.php.net to get a copy of this message | ||
Using a return statement inside a finally block will override any other return statement or thrown
exception from the try block and all defined catch blocks. Code execution in the parent stack will
continue as if the exception was never thrown.
Frankly this is a good design decision because it means I can optionally dismiss all thrown
exceptions from 1 or more catch blocks in one place, without having to nest my whole try block
inside an additional (and otherwise needless) try/catch block.
This is the same behavior as Java, whereas C# throws a compile time error when a return statement
exists inside a finally block. So I figured it was worth pointing out to PHP devs who may not have
any exposure to finally blocks or how other languages do it.
<?php
function asdf()
{
try {
throw new Exception('error');
}
catch(Exception $e) {
echo "An error occurred";
throw $e;
}
finally {
//This overrides the exception as if it were never thrown
return "\nException erased";
}
}
try {
echo asdf();
}
catch(Exception $e) {
echo "\nResult: " . $e->getMessage();
}
?>
The output from above will look like this:
An error occurred
Exception erased
Without the return statement in the finally block it would look like this:
An error occurred
Result: error
----
Server IP: 72.52.91.14
Probable Submitter: 72.52.91.14
----
Manual Page -- http://php.net/manual/en/language.exceptions.php
Edit -- https://master.php.net/note/edit/114207
Del: integrated -- https://master.php.net/note/delete/114207/integrated
Del: useless -- https://master.php.net/note/delete/114207/useless
Del: bad code -- https://master.php.net/note/delete/114207/bad+code
Del: spam -- https://master.php.net/note/delete/114207/spam
Del: non-english -- https://master.php.net/note/delete/114207/non-english
Del: in docs -- https://master.php.net/note/delete/114207/in+docs
Del: other reasons-- https://master.php.net/note/delete/114207
Reject -- https://master.php.net/note/reject/114207
Search -- https://master.php.net/manage/user-notes.php