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?
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);
Import stdlib and call exit while passing 0.
import std.c.stdlib;
exit(0);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With