Exception Safe Programming

Tyler Knott tywebmail at mailcity.com
Sat Feb 24 20:29:33 PST 2007

Saaa wrote:
> That is exactly what I originally thought, but why then is that piece of 
> code a example of how to ...
> oh wait... if f=dofoo() fails, f is still unchanged and the correct thing to 
> do is to exit the function through an exception.
> never mind, but thanks :)

When an exception is thrown and not caught, the compiler unwinds the callstack until it finds a handler.  What this 
means is that if a function throws an exception then the program will look for the closest call inside a try block with 
a following catch block that will accept the type of the exception (or a type the exception is implicitly castable to). 
  So, for example:

import std.stdio;

class MsgClass
	this() { writefln("MsgClass constructed."); }
	~this() { writefln("MsgClass destructed."); }

class TestException : Exception
	this(char[] msg) { super(msg); }

void thrower()
	writefln("Throwing exception.");
	throw new TestException("This is an exception");

int inBetween()
	//Destructs after the exception because its scope is destroyed by the exception
	scope MsgClass i = new MsgClass();
	writefln("Returning 5..."); //Never prints
	return 5; //Function never returns

void main()
	int x;
		x = inBetween(); //x is never assigned
	catch(Exception e)
		writefln("Caught exception: ", e);
	writefln("The value of x is: ", x); //x = 0

This code will output the following with thrower() called:

MsgClass constructed.
Throwing exception.
MsgClass destructed.
Caught exception: This is an exception
The value of x is: 0

And this without:

MsgClass constructed.
Returning 5...
MsgClass destructed.
The value of x is: 5

More information about the Digitalmars-d-learn mailing list