Re: [RFC] Optional Catch Block Body
| From: | Oladoyinbo Vincent | Date: | Thu, 31 Jul 2025 07:57:00 +0000 |
| Subject: | Re: [RFC] Optional Catch Block Body | ||
| References: | 1 2 3 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-128331@lists.php.net to get a copy of this message | ||
Interesting catch, but i have been thinking of a better approach of
catching errors without the try and catch block madness.
Here is my suggestion:
```php
try (Exception $e) {
// define logic
}
if ($e) {
// execute code...
}
```
looks way more clean and structured, what do y'all think?
Just a suggestion though.
On Thu, 31 Jul 2025, 8:41 am Mihail Liahimov, <91liahim@gmail.com> wrote:
> Hi, Rob!
>
> Good point! I also know one another case when empty catch block are useful.
>
> When we want to avoid returning null values, we resort to using exceptions
> so that the client code can somehow handle the absence of values.
> For example:
>
> if ($user->getName() !== null) {
> $this->doSomethingWithUserName($user->getName());
> }
>
> We usually add an exception inside such getters if there is no value:
>
> try {
> $this->doSomethingWithUserName($user->getName());
> } catch (UserNameIsNull);
>
> This is useful when we need to "do nothing" when there is no value. In my
> opinion, this code looks more declarative.
>
> We can do something like this also with repositories:
>
> try {
> $post = $this->postRepository->get($postId);
>
> // do something with post
> } catch (PostNotFound);
>
> But again, there is a fine line between situations where an empty body of
> a catch block is reasonable and when it is not.
>
> чт, 31 июл. 2025 г. в 12:13, Rob Landers <rob@bottled.codes>:
>
>> even in my case, my empty catches have lengthy comments describing why
>> they are empty in case a user steps into it, so they can better understand
>> how the framework works.
>>
>> — Rob
>>
>