close program by code

H. S. Teoh via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Jun 26 07:28:22 PDT 2014


On Thu, Jun 26, 2014 at 01:23:17PM +0000, Chris Nicholson-Sauls via Digitalmars-d-learn wrote:
> On Thursday, 26 June 2014 at 11:07:37 UTC, Rene Zwanenburg wrote:
> >
> >They won't. Same for module destructors.
> >
> >If you need those to work, another option is to throw some custom
> >Exception type which is only caught in main.
> 
> I really wish this wasn't the answer, but for some programs I've had
> to resort to it myself.  For at least one I've defined an Exception
> type that carries a status code payload to be returned by main.  D
> needs its own exit().

I've done the same for my own programs:

	class ExitException : Exception
	{
		int status;
		this(int _status, string file=__FILE__,
			size_t line=__LINE__)
		{
			super(file,line);
			status = _status;
		}
	}
	void exit(int status=0) {
		throw new ExitException(status);
	}
	int main(string[] args) {
		try {
			...
			return 0;
		} catch(ExitException e) {
			return e.status;
		} catch(Exception e) {
			... // real exception here
			return 1;
		}
	}

It works reasonably well for single-threaded program, but as the
following bug states, there's no nice way to terminate a multithreaded
program:


> There's been this request in the bugzilla since 2009:
> https://issues.dlang.org/show_bug.cgi?id=3462

If you have any good ideas, please chime in on the bug report!


T

-- 
"I'm not childish; I'm just in touch with the child within!" - RL


More information about the Digitalmars-d-learn mailing list