I'm using Delphi (7-2010) and trying to figure out a good way to handle exceptions while freeing forms of an application. The application has several forms that are owned by the Application object. When the user logs out, I need to free all of the existing forms so no user state is maintained and then show the login dialog for the next user who logs in.
Occasionally, an exception happens while trying to free one of the forms. That leaves the form in memory, but in an unknown/unusable state, so I can't re-use the form for the next user, and I also can't get rid of it from memory. Because the forms are owned by the application, I can't directly create a new version of the form for the next user, since it would cause the "A component named MyForm already exists" error from the VCL, and I'm bit averse to having old form instances in memory anyway.
I'd like to see what others would do in this case. Here are some ideas:
- Terminate the application when you get these exceptions, so you are sure to wipe the slate clean. The user is logging out anyway, so they are likely done with the app. Optionally restart the app if desired.
- Make the forms not owned by the Application, so you can create multiple instances of them, and make sure any non-freeable/broken forms are at least hidden.
- Dynamically generate the name of each form, or set it to blank, so there are never duplicate names, and no "already exists" errors from the VCL.
- Write an application so well that there are never exceptions when freeing objects (unrealistic - I need a contingency plan for unexpected errors).
My Solution was one of the original ideas above. I added a try/except block around the loop that frees the forms, and if there is an exception, I show the error message to the user without raising it, and then call ExitProcess(0) to immediately kill the application.