April 14, 2018 —John Koster
The rescue
function can be used to attempt execution of an operation that has the potential to throw an exception. The rescue
function will allow you to specify a default value, through the $rescue
parameter that will be returned if the operation fails.
The rescue
helper function will log invoke the report
helper function on the inner exception if the operation fails.
The signature of the rescue
function is:
1function rescue(2 callable $callback,3 $rescue = null4);
The following examples are equivalent:
1$value = rescue(function () {2 throw new Exception('This will always fail');3}, function () {4 return 'Hello, Universe';5});
Using try/catch Control Structure
1$value = '';2 3try {4 throw new Exception('This will always fail');5} catch (Exception $e) {6 report($e);7 8 $value = 'Hello, Universe';9}
After both code examples have executed, the value of $value
would be Hello, Universe
. In the first example, you will notice that we are able to supply a callback as the default value when calling rescue
; this is because the default value is evaluated using the value
helper function before it is returned.
∎
The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.