'Exceptions and DLL in Delphi

What is the right way to handle exceptions thrown from inside a DLL in Delphi?

Something like this

on E : ESomeException do ...

or

if (E is ESomeException) then ...

fails, because of the separate type registries of the DLL and the main application.



Solution 1:[1]

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 ...

Solution 2:[2]

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.

Solution 3:[3]

Sometimes you do not have control over a DLL and cannot avoid having trouble with exceptions.

We, for instance, had a problem with a function in an external DLL that was blocked by AV software settings ("ransomware protection") leading to access violations in Delphi.

The following code is working for us:

var
    O: TObject;
    Msg: AnsiString;   //type depending on DLL
begin
    try
        CallExternalDll(...);
    except
        //on E: Exception do might lead to access violations
        //because the exception might not be of type Exception
        O := ExceptObject;
        //Depending on the DLL this or an other cast might 
        //or might not be necessary:
        Msg := PAnsiChar(Exception(O).Message);

        raise Exception.Create(Msg);
    end;
end;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Deltics
Solution 2
Solution 3 yonojoy