1

I am trying to load a library in my Delphi project and this library can be in two locations. So to load it, I am using the following code:

  try
    FHandle:=LoadLibrary(('some\address'));
  except on EAccessViolation do
    FHandle:=LoadLibrary(('another\address'));
  end;

however, I am having a problem because it never reaches the exception, I got the error that there was an Access Violation but it doesn't try to load from the other address...

does any one have an idea of the reasons?

thanks,

Felipe
  • 253
  • 4
  • 11
  • LoadLibrary Windows API just returns NULL on error. – Alex F Sep 11 '13 at 13:28
  • But what should I use to track this error and to have an exception to it? – Felipe Sep 11 '13 at 13:29
  • 2
    If first LoadLibrary returns NULL (FHandle is NULL), call LoadLibrary again with another file name. – Alex F Sep 11 '13 at 13:34
  • Why is this question protected? I believe @ChrisF has a good day – RBA Sep 11 '13 at 18:10
  • @RBA - it was attracting spam answers (now deleted obviously). – ChrisF Sep 11 '13 at 20:12
  • 1
    @ChrisF It seems that an awful lot of spam answers, on an awful lot of questions made it onto the site. I wonder if more could be done to block them at source. I mean, thanks for all the hard work dealing with them, but I'm sure you diamond mods would prefer to be doing other stuff. – David Heffernan Sep 11 '13 at 22:38

2 Answers2

4

LoadLibrary does not raise exceptions. It is a Win32 function. Consult the documentation and you will see that it returns NULL if it fails.

Your code should be:

FHandle := LoadLibrary('some\address');
if FHandle = 0 then
  FHandle := LoadLibrary('another\address');
if FHandle = 0 then
  // handle the error, probably by raising an exception

Another option might be to use FileExists to check which of your possible locations contains the file.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
1

To add to David's answer, if the function does return null i.e. failed, you can get the error with GetLastError(), see:

http://msdn.microsoft.com/en-us/library/ms679360.aspx

a list of error codes can be found here:

http://msdn.microsoft.com/en-us/library/ms679360.aspx

You can use the result from GetLastError to raise and exception yourself with a meaningfull exception type and description.

Johan
  • 74,508
  • 24
  • 191
  • 319