How to intercept (Control + C) KeyboardInterrupt in a Try/Catch block?

Dejan Lekic dejan.lekic at gmail.com
Fri Apr 24 11:41:47 UTC 2026


On Friday, 24 April 2026 at 11:02:07 UTC, Marvin wrote:
> I'm having trouble intercepting (Control + C) KeyboardInterrupt 
> in a Try/Catch block.
>
> Could someone explain how to do this in D?

Catching signal(s) has nothing to do with exceptions.
Here is a minimal example to help you start:

```d
import core.stdc.signal : signal, SIGINT;
import core.thread : Thread;
import core.time : dur;
import std.stdio : writeln;

__gshared bool stop = false;

extern(C) nothrow @nogc void onSigInt(int) {
     stop = true;
}

void main() {
     signal(SIGINT, &onSigInt);
     writeln("Running... press Ctrl-C to stop.");

     while (!stop) {
         writeln("working...");
         Thread.sleep(dur!"seconds"(1));
     }

     writeln("Caught Ctrl-C, exiting cleanly.");
}
```

You can throw an exceptiob somewhere in the loop throw an 
exception, and have some logic that handles it, but I will leave 
that to you as an exercise, or you explain what you need to do 
and we can help you there.


More information about the Digitalmars-d-learn mailing list