Date: Wed, 22 Nov 2023 13:55:08 +0100
On 22/11/2023 12:47, Giuseppe D'Angelo via Std-Proposals wrote:
> Il 22/11/23 12:31, sasho648 via Std-Proposals ha scritto:
>>
>> So in my experience the biggest issue I had with using try-catch is
>> for example when I try to construct a reference within try-catch - in
>> order to capture only the exception that could occur there:
>>
>> try {
>> auto &ref = func();
>> }
>> catch(...) {
>> }
>>
>> Problem here is:
>>
>> You either have to use reference wrapper or something like that if
>> you want to handle only the exception that could potentially be
>> thrown by func. And still it would be ugly.
>
> But what should `ref` refer to if `func()` throws?
>
If I remember correctly, what Java does is that the scope of the
variable declared in the try statement is the try block, so it cannot be
used outside it. There is no such thing as `ref` if `func()` throws. I
think it's the way to go.
By the way, such syntax would help for cases where we want to declare a
const value from something that can throw:
try(const Foo foo = build_foo()) {
use_foo(foo);
}
The current alternative is to either use a non-const variable that will
be set in the try block:
Foo foo; // can't be const
try {
foo = build_foo();
} catch(...) {
return;
}
use_foo(foo);
Or to put all the code in the try block:
try {
const Foo foo = build_foo();
use_foo(foo);
} catch(...) {
// also catches exceptions thrown by use_foo().
return;
}
None of these is satisfying IMHO.
Julien
> Il 22/11/23 12:31, sasho648 via Std-Proposals ha scritto:
>>
>> So in my experience the biggest issue I had with using try-catch is
>> for example when I try to construct a reference within try-catch - in
>> order to capture only the exception that could occur there:
>>
>> try {
>> auto &ref = func();
>> }
>> catch(...) {
>> }
>>
>> Problem here is:
>>
>> You either have to use reference wrapper or something like that if
>> you want to handle only the exception that could potentially be
>> thrown by func. And still it would be ugly.
>
> But what should `ref` refer to if `func()` throws?
>
If I remember correctly, what Java does is that the scope of the
variable declared in the try statement is the try block, so it cannot be
used outside it. There is no such thing as `ref` if `func()` throws. I
think it's the way to go.
By the way, such syntax would help for cases where we want to declare a
const value from something that can throw:
try(const Foo foo = build_foo()) {
use_foo(foo);
}
The current alternative is to either use a non-const variable that will
be set in the try block:
Foo foo; // can't be const
try {
foo = build_foo();
} catch(...) {
return;
}
use_foo(foo);
Or to put all the code in the try block:
try {
const Foo foo = build_foo();
use_foo(foo);
} catch(...) {
// also catches exceptions thrown by use_foo().
return;
}
None of these is satisfying IMHO.
Julien
Received on 2023-11-22 12:55:11