D:如何退出主?

时间:2015-10-10 13:51:54

标签: d main exit

终止/退出主要功能的D方式是什么?

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
}

我尝试使用Google搜索并找到下一个问题D exit statement 有建议使用C退出功能。现代D中是否有任何新的未来,是否允许它更优雅?

2 个答案:

答案 0 :(得分:5)

如果你没有紧急出口,那么你想清理一切。我为此目的创建了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;
    }
}

您对main()功能进行编码,然后再

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

在您需要退出时,请致电

throw new ExitException(1);

答案 1 :(得分:4)

导入stdlib并在传递0时调用exit。

 import std.c.stdlib;
    exit(0);