Exceptions and DLLs in Delphi

What is the correct way to handle exceptions from a DLL in Delphi?

Something like that

on E : ESomeException do ... 

or

 if (E is ESomeException) then ... 

crashes due to certain types of DLL registries and the main application.

+4
source share
4 answers

For pure exceptions, DLLs are not allowed to cross the boundary of a DLL (such as Deltics ) - no matter what language.

You get all kinds of problems there , especially because you don’t know what language, RTL, memory manager, etc. each side of the border.

So, you are back to the classic error handling paradigm:

Instead of DLLs, you can use BPL packages (as suggested by Lars ): there you know that both sides will use the same RTL and memory manager.

Both packages and the BPL usually give you a nightmare with the version anyway (too many degrees of freedom).

A more rigorous solution is to switch to a monolithic executable; this solves both problems:

  • much easier version control
  • only one RTL and memory manager is guaranteed

- Jeroen

PS: I made this an optional answer because it makes it easier to insert links.

+8
source

The safest way is to exclude exceptions from the DLL first.

But if you do not control the source of the DLL and therefore cannot guarantee this, you can still check the name of the exception class:

 if SameText(E.ClassName, 'ESomeException') then ... 
+5
source

If you use runtime packages (at least rtlxx.bpl) for your application and your DLL, then both types are of the same type and it will work. Of course, this limits the use of your DLL to Delphi / BCB only.

Another solution does not use exceptions at all, as Deltics suggests. Return error codes.

Or use COM. Then you can have exceptions and not limit your DLL to Delphi only.

+3
source

This workaround does this for me:

  function ExceptionMatch (Exc : Exception; ExcClass : TClass) : Boolean; var CurrClass : TClass; begin CurrClass := Exc.ClassType; while (CurrClass <> nil) do begin if SameText (CurrClass.ClassName, ExcClass.ClassName) then Exit (True); CurrClass := CurrClass.ClassParent; end; Result := False; end; 

I am ready for you to destroy it :)

What is wrong with this approach? What is potentially dangerous?

-2
source

Source: https://habr.com/ru/post/1301086/


All Articles