Trailing catch on function?

Steven Schveighoffer via Digitalmars-d digitalmars-d at puremagic.com
Mon Nov 7 19:14:43 PST 2016


On 11/6/16 11:30 PM, Manu via Digitalmars-d wrote:
> Hey people, I'm passing lots of D function pointers to C, and naturally,
> the C api expects the fp signatures are all nothrow.
>
> Which means, my D functions all look like this:
>
> void callback() nothrow
> {
> try
> {
> ...lots of code...
> }
> catch (Exception e)
> {
> ...log error or abort...
> }
> }
>
>
> I'm generally annoyed by all the extra indentation.
> Since nothrow is a central thing in D, I wondered if it would be
> reasonable to allow a nice little bit of sugar to assist working with
> nothrow that would look like this:
>
> void catchingCallback() nothrow
> {
> ...lots of code...
> }
> catch (Exception e)
> {
> ...log error or abort...
> }
>
> Syntactically similar to the existing in/out sections, although I think
> it would be nicer at the bottom...
> It's simply a lowering which wraps the entire function body scope in a try.

the tough thing about this is, what is in scope inside the catch? You 
are outside the function, so the only thing available is the exception.

Being stupid, I thought maybe this might work:

nothrow void catchingCallback() try
{
}
catch(Exception e)
{
}

Thinking "hey, a function body is like a scope, maybe I can just do one 
statement instead!"

But it doesn't work. However, this isn't far off:

void catchingCallBack() nothrow {try
{
}
catch(Exception e)
{
}}

Another solution may be to write your function as normal, and then mixin 
definitions for a nothrow version of it. Of course, this means you have 
to handle all your exceptions the same way.

-Steve


More information about the Digitalmars-d mailing list