D: How to get out of the main?

What is the D path for terminating / exiting the main function?

import std.stdio;
import core.thread;

void main()
{
    int i;
    while (i <= 5)
    {
        writeln(i++);
        core.thread.Thread.sleep( dur!("seconds")(1) );
    }
    if (i == 5) 
    {
        writeln("Exit");
        return; // I need terminate main, but it look like break do exit only from scope
    }
    readln(); // it still wait a user input, but I need exit from App in previous step
}

I tried to do a googling search and found the following question. D exit statement is there a suggestion to use the C exit function. Are there any new futures in modern D that can make this more elegant?

+4
source share
2 answers

Import stdlib and end the call when passing 0.

 import std.c.stdlib;
    exit(0);
+3
source

If you are not doing an emergency exit, you want to clear everything. For this purpose, I created ExitException:

class ExitException : Exception
{
    int rc;

    @safe pure nothrow this(int rc, string file = __FILE__, size_t line = __LINE__)
    {
        super(null, file, line);
        this.rc = rc;
    }
}

You code the function main()and then

int main(string[] args)
{
    try
    {
        // Your code here
    }
    catch (ExitException e)
    {
        return e.rc;
    }
    return 0;
}

The moment you need to exit, you call

throw new ExitException(1);
+4

Source: https://habr.com/ru/post/1611096/


All Articles