PDA

View Full Version : [try try ... finally ... end; except ... end;]



Ñuño Martínez
27-08-2008, 06:02 PM
Hello everybody.

I have a problem with exceptions, I hope you can help me.

At the main file I have this simple code:BEGIN
TRY
TheGame := TEnjambre.Create;
TRY
TheGame.Run;
FINALLY
TheGame.Free;
END;
EXCEPT
ON Error: Exception DO
al_message (Error.Message);
END;
END.
In the "TheGame.Run" method I call a "setup" method that includes this code: ...
{ Try to set graphic mode. }
al_set_color_depth (Bits);
IF al_set_gfx_mode (Driver, Width, Height, 0, 0) <> 0 THEN
RAISE GfxExceptionMng.Create ('Cannot set graphic mode!');
...
...where the GfxExceptionMng class is just an extension of the Exception class.

If I'm right, if I provide a wrong graphic mode configuration then the application should show a message box with the text "Cannot set graphic mode!" inside, but actually it doesn't. The screen flicks a bit and the game quietly exits.

Lazarus' debugger said that "Project raised exception class 'GfxExceptionMng'" but the "finally .. end;" block nor the "except .. end;" block were executed after pressing [F9].

Does somebody know where is the problem? How to fix this? Thanks.

JSoftware
27-08-2008, 06:41 PM
How about this. Your constructor shouldn't throw exceptions anyways since, you would risk yourself weird halfinitialized class instances that way. That's the priciple I usually design my own classes after anyways..

BEGIN
TheGame := TEnjambre.Create;
TRY
TheGame.Run;
EXCEPT
ON Error: Exception DO
al_message (Error.Message);
END;
TheGame.Free;
END.

Almindor
15-11-2008, 10:52 AM
If an exception is thrown withing a constructor which is creating (remember, constructors can be called on instances normally as methods), then the new instance is freed automatically.

There's nothing wrong with raising exceptions this way, unlike in C++ where you end up with possible stack/heap mess.