newbie problem with nothrow

Mike Parker via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Oct 31 23:54:22 PDT 2016


On Monday, 31 October 2016 at 16:55:51 UTC, WhatMeWorry wrote:
>
> Is there a way to turn off nothrow or work around it? Because 
> to me it looks like nothrow prevents me from doing anything 
> useful.
>
> extern(C) void onKeyEvent(GLFWwindow* window, int key, int 
> scancode, int action, int modifier) nothrow
> {
>     if(queue.roomInQueue())
>     {
>         auto event = new Event;
>         event.type = EventType.keyboard;
>         event.keyboard.key = cast(Key) key;
>
>         // etc.
> }
>
> Error: function 'event_handler.CircularQueue.roomInQueue' is 
> not nothrow
> Error: function 'event_handler.onKeyEvent' is nothrow yet may 
> throw
>
>
> The compiler wouldn't let me just remove "nothrow" from the 
> function. I tried a kludge where I had this function just pass 
> all its parameters to another throwable function, but this 
> caused errors as well.
>
> So I'm stuck.  Anyone know how to proceed.
> Thanks.

If you can't change the interface of CiricularQueue to be nothrow 
and don't want to wrap everything in a try...catch block, then 
just use a dynamic array. You can also use the old C union trick 
to avoid the need to allocate every event. That's the same thing 
SDL does. Something like this:

```
enum EventType {
    key,
    mouse,
}

struct KeyEvent {
    EventType type;
    ...

    this(...)
    {
         this.type = EventType.key;
         ...
    }
}

struct MouseEvent {
    EventType type;
    ...

    this(...)
    {
         this.type = EventType.mouse;
         ...
    }
}

union Event {
    EventType type;
    KeyEvent key;
    MouseEvent mouse;
}

Event[] eventq;
extern(C) void onKeyEvent(GLFWwindow* window, int key, int 
scancode, int action, int modifier) nothrow {
     Event event;
     event.key = KeyEvent(window, key, scancode, action, modifier);
     eventq ~= event;
}
```



More information about the Digitalmars-d-learn mailing list