Exception Safe Programming
Saaa
empty at needmail.com
Sun Feb 25 07:06:48 PST 2007
Thanks,
I understand it now: place 'x = inBetween();' before 'try' and the catch
will never run (crash)
>
> 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();
> thrower();
> writefln("Returning 5..."); //Never prints
> return 5; //Function never returns
> }
>
> void main()
> {
> int x;
> try
> {
> 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