Try blocks are trying
FeepingCreature
feepingcreature at gmail.com
Mon Oct 11 11:42:52 UTC 2021
On Monday, 11 October 2021 at 11:05:47 UTC, bauss wrote:
> On Monday, 11 October 2021 at 09:27:30 UTC, FeepingCreature
>> `export try` is the only feasible approach I can see offhand.
>
> Using alias this, opAssign and a boolean value you can actually
> do something like this:
>
> ```d
> public struct BindOnce(T)
> {
> private bool _isSet;
> private T _value;
>
> alias _value this;
>
> void opAssign(T rhs)
> {
> if (_isSet)
> {
> throw new Error("The value has already been set.");
> }
>
> _isSet = true;
> _value = rhs;
> }
>
> string toString() { return to!string(_value); } // Required
> for writeln
> }
> ```
>
> Example Usage:
>
> ```
> int getNumber(int input)
> {
> if (input == 0) throw new Exception("This function doesn't
> allow multiplications of zero.");
> return input * 2;
> }
>
> void main()
> {
> BindOnce!int n;
> try
> {
> n = getNumber(20);
> //n = getNumber(40); // Uncommenting this line will
> throw the error "The value has already been set."
>
> writeln(n);
> }
> catch (Exception e)
> {
> writeln(e);
> writeln(n);
> }
> }
> ```
>
> Of course this assumes you're able to allow runtime errors and
> that you don't blindly catches them and ignores them either
> (which you shouldn't as Error shouldn't be recoverable!)
I almost don't want to say it.
Cough immutable cough...
That's why this really needs language support.
(Also I'd just use `Nullable` or `Rebindable` irl.)
More information about the Digitalmars-d
mailing list