Skip to content

Commit ed956d7

Browse files
authored
Document exception chaining (#3855)
This is already documented as a user note, but the note does not explain what happens if both exceptions already have a previous exception. Here is what I believe is the related piece of code: ``` /* Chain potential exception from wrapping finally block */ if (Z_OBJ_P(fast_call)) { if (ex) { if (zend_is_unwind_exit(ex) || zend_is_graceful_exit(ex)) { /* discard the previously thrown exception */ OBJ_RELEASE(Z_OBJ_P(fast_call)); } else { zend_exception_set_previous(ex, Z_OBJ_P(fast_call)); } } else { ex = EG(exception) = Z_OBJ_P(fast_call); } } ``` The note: https://www.php.net/manual/en/language.exceptions.php#129177
1 parent 1651836 commit ed956d7

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

language/exceptions.xml

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,12 @@
7979
is executed. Additionally, if the &finally; block also contains a &return; statement,
8080
the value from the &finally; block is returned.
8181
</para>
82+
<para>
83+
Another notable interaction is between an exception thrown from within a &try; block,
84+
and an exception thrown from within a &finally; block. If both blocks throw an exception,
85+
then the exception thrown from the &finally; block will be the one that is propagated,
86+
and the exception thrown from the &try; block will used as its previous exception.
87+
</para>
8288
</sect1>
8389

8490
<sect1 annotations="chunk:false" xml:id="language.exceptions.exception-handler">
@@ -359,6 +365,38 @@ try {
359365
<screen>
360366
<![CDATA[
361367
It did not work
368+
]]>
369+
</screen>
370+
</example>
371+
<example>
372+
<title>Exception in try and in finally</title>
373+
<programlisting role="php">
374+
<![CDATA[
375+
<?php
376+
377+
try {
378+
try {
379+
throw new Exception(message: 'Third', previous: new Exception('Fourth'));
380+
} finally {
381+
throw new Exception(message: 'First', previous: new Exception('Second'));
382+
}
383+
} catch (Exception $e) {
384+
var_dump(
385+
$e->getMessage(),
386+
$e->getPrevious()->getMessage(),
387+
$e->getPrevious()->getPrevious()->getMessage(),
388+
$e->getPrevious()->getPrevious()->getPrevious()->getMessage(),
389+
);
390+
}
391+
]]>
392+
</programlisting>
393+
&example.outputs;
394+
<screen>
395+
<![CDATA[
396+
string(5) "First"
397+
string(6) "Second"
398+
string(5) "Third"
399+
string(6) "Fourth"
362400
]]>
363401
</screen>
364402
</example>

0 commit comments

Comments
 (0)