Every once in a while I discover an answer I have not yet put on my blog, especially as related answer are always interesting.
This is one that didn’t make it until now: [Wayback/Archive] Exceptions and DLL in Delphi – Stack Overflow (thanks [Wayback/Archive] jpfollenius, [Wayback/Archive] Deltics and [Wayback/Archive] Lars Truijens)
Q
What is the right way to handle exceptions thrown from inside a DLL in Delphi?Something like thison E : ESomeException do ...
orif (E is ESomeException) then ...
fails, because of the separate type registries of the DLL and the main application.A
For pure DLL’s exceptions are not allowed to cross the DLL boundary (like Deltics mentions) – no matter what language.
You get [Wayback/Archive] all sorts of trouble there, especially because you don’t know which language, RTL, memory manager, etc, is on each side of the boundary.
So you are back to the classic error handling paradigm:
- error codes (similar to HResult)
- error messages (similar to [Wayback/Archive] GetLastError)
Instead of DLL’s, you could use BPL packages (as Lars suggested): there you know that both sides will use the same RTL and memory manager.
Both packages and BPL usually give you a versioning nightmare anyway (too many degrees of freedom).
A more rigorous solution is to go for a monolithic executable; this solves both problems:
- much easier versioning
- guaranteed only one RTL and memory manager
–jeroen
PS: I’ve made this an additional answer because that allows for easier pasting of links.
A
The safest way is to not allow exceptions to “escape” from the DLL in the first place.
But if you have no control over the source of DLL and are therefore unable to ensure this, you can still test the exception class name:
if SameText(E.ClassName, 'ESomeException') then ...
A
If you use runtime packages (at least rtlxx.bpl) for both your application and your dll, then both have the same type and it will work. Of course this limits the use of your dll to Delphi/BCB only.
Another solution is not using exceptions at all like Deltics suggest. Return error codes.
Or use COM. Then you can have exceptions and not limit your dll to Delphi only.
--
jeroen