Type Inference and Try Blocks

Adam D. Ruppe destructionator at gmail.com
Tue Jan 21 01:06:14 UTC 2020


On Monday, 20 January 2020 at 23:16:07 UTC, Henry Claesson wrote:
> This isn't a D-specific "problem", but there may be D-specific 
> solutions.
> I have a function `doSomething()` that returns a Voldemort 
> type, and this same function also throws. So, there's this:
>
> try {
>     auto foo = doSomething();
> } catch (AnException e) {
>     // Do stuff
> }

I'd suggest just doing

try {
     auto foo = doSomething();
     // use foo right here!
} catch(AnException e) {
     // do other stuff
} catch(OtherException e) {
    // reminder you can do this too btw
}


That is, put ALL the use of foo inside the one try block, don't 
keep nesting - only try/catch when you can specifically recover 
or add information to it at that particular point. If you can't 
do that, just keep going. try/catch over individual functions is 
often (though not always) poor design.

If you really do need the variable outside, you can do

typeof(doSomething(args...)) foo;
try {
   foo = doSomething()
}

too to declare the var outside. But first I'd try getting it all 
in that try block.

You can also do helper functions for some cases too btw

auto getfoo() {
    try return doSomething();
    catch(MyException e) { return alternative(); }
}

and remember you can define that right inside the function; 
nested functons rock.



More information about the Digitalmars-d-learn mailing list