orce exit, possible?

H. S. Teoh hsteoh at quickfur.ath.cx
Thu Nov 21 12:12:15 PST 2013


On Thu, Nov 21, 2013 at 08:38:18PM +0100, Kelet wrote:
> On Thursday, 21 November 2013 at 19:27:51 UTC, seany wrote:
> >is there a keyword like exit, that i can call  in any function to
> >force the code to exit with a particular status to the shell?
> >
> >I tried the word exit itself, it did not work
> 
> C's exit function should be available to you if you
> import std.c.stdlib;

That works, but bypasses D runtime cleanup functions.

My workaround is to make use of the exception system:

	class ExitException : Exception {
		int status;
		this(int _status) {
			super("Program exit");
			status = _status;
		}
	}

	// never returns
	void exit(int status=0) { throw new ExitException(status); }

	int main(string[] args) {
		try {
			// actual code here
			...
			exit(1); // should exit with status 1
			...
		} catch(ExitException e) {
			return e.status;
		} catch(Exception e) {
			// do your usual exception handling here
		}
		return 0;
	}

It's kinda ugly, but you could encapsulate this in a custom library: say
rename main() to dmain(), then have the library provide the actual
main() with the try-catch block, and possibly with some other niceties
as well. Then you could just use this library in all your programs.

The use of exceptions may slow things down a bit, but at program exit
time, that's really the least of your concerns so it shouldn't matter at
all.


T

-- 
Latin's a dead language, as dead as can be; it killed off all the Romans, and now it's killing me! -- Schoolboy


More information about the Digitalmars-d-learn mailing list