D:如何从main退出?

Dmi*_*kov 4 program-entry-point d 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
}
Run Code Online (Sandbox Code Playgroud)

我试图进行谷歌搜索,发现下一个问题D退出语句 有建议使用C退出功能。现代D中是否有任何新的期货,可以使它更优雅?

小智 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

您编写main()函数,然后像

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

在您需要退出的位置致电

throw new ExitException(1);
Run Code Online (Sandbox Code Playgroud)