C++ Logo

std-proposals

Advanced search

[std-proposals] try else syntax for validity check

From: Filip <fph2137_at_[hidden]>
Date: Sun, 16 Feb 2025 17:52:48 +0100
Hi everyone,
I want to present to you possible new syntax that would allow for an easy improvement of both safety and user experience with any pointer/optional type.

We usually need to check many times the validity of an object, which is done with an:
if(wrapperType) // use wrapper
I frequently use code like:
return ptrType->get(0)->getParamsPtr()->getName();

With multiple sub wrappers or returned pointers I would love to be simply to reuse try keyword in the following way:

try return ptrType->optType.otherWrapper.value;
else return defaultValue;

In this example try keyword would check if every but last element is castable to bool, allows for an access with either . or ->
Then it would cast element by element in this statement and only go to the next element when the cast would succeed and return true.

Possibly single try could also be used with a function like:
try ptrType->returnedFunc();

The function would be executed only if pointer is not null.
It could also allow for a bit more complex syntax with catches, however it would then expand the meaning to also catch exceptions:

try return ptrType->value;
else return defaultValue;
catch (exception e) return exceptionValue;

Equivalent to wrapping entire try else with try catch.

Cheers, Filip

Received on 2025-02-16 16:53:01