Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

D: How to exit from main?

What it the D way to terminate/exit 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's look like break do exit only from scope
    }
    readln(); // it's still wait a user input, but I need exit from App in previous step
}

I tried to googling and found next question D exit statement there is suggestion to use C exit function. Is there any new futures in modern D, that are allow to do it's more elegant?

like image 320
Dmitry Bubnenkov Avatar asked Jan 08 '23 09:01

Dmitry Bubnenkov


2 Answers

If you are not doing an emergency exit then you want to clean up everything. I created an ExitException for this purpose:

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 your main() function then like

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

At the point where you need to exit you call

throw new ExitException(1);
like image 157
Kai Nacke Avatar answered Jan 31 '23 19:01

Kai Nacke


Import stdlib and call exit while passing 0.

 import std.c.stdlib;
    exit(0);
like image 22
Sreejith Nair Avatar answered Jan 31 '23 19:01

Sreejith Nair