How to avoid throwing an exceptions for a built-in function?

Stanislav Blinov via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed May 10 14:19:21 PDT 2017


On Wednesday, 10 May 2017 at 15:35:24 UTC, k-five wrote:
> On Wednesday, 10 May 2017 at 14:27:46 UTC, Stanislav Blinov 
> wrote:
>> On Wednesday, 10 May 2017 at 13:27:17 UTC, k-five wrote:
>>
>>> Thanks, but I know about what are you saying. The 
>>> user_apply[4] has so many possibilities and I cannot use 
>>> if-else
>>
>> That doesn't sound right. Either you've already handled all 
>> the possible cases and thus expect the to! to not throw (can 
>> specify that i.e. via std.exception.assumeWontThrow), or, as 
>> you're saying, it's much more than an if-else, but in that 
>> case exception will be thrown on invalid input.
>
> ------------------------------------------------------------------
>
> I know. But I am saying that I do not want to take care of any 
> exceptions.
> I just wanted to write:
>
> int variable = to!int( string-type );
>
> In fact something like using "no throw" is a function:
> void init( ... ) nothrow {
>     ...
>     int variable = to!int( string-type );
>     ...
> }
>
> but this is not valid.
>
> Thanks anyway and I will test: Function 
> std.exception.assumeWontThrow at this link:
> https://dlang.org/library/std/exception/assume_wont_throw.html

I don't understand. If you don't want to take care of exceptions, 
then you just don't do anything, simply call to!int(str). If an 
exception is thrown, it'll propagate further up the stack, until 
you either handle it or abort the program. "nothrow" does not 
turn off exceptions, it simply forbids throwing them in the 
enclosing scope (i.e. calling anything that might throw is not 
allowed).
Or do you mean that you've already made sure that the user input 
is valid such that to!int() will never throw with it? In that 
case, yes, assumeWontThrow is a way to express that. But then, 
the only way you can be sure of that is if you've already parsed 
the input yourself, so I'm not clear on the intent.
Alternatively, if what you're calling still might throw but you 
don't want to deal with try/catch blocks, there's 
collectException function in std.exception that'll give you the 
exception if it was thrown and let you deal with it without using 
try/catch.


More information about the Digitalmars-d-learn mailing list