title: Handling an exception thrown from inside a dll
body: <p>I'm working on a project for school in which a dll is loaded. </p>
  
  <p>The dll that is loaded is a bridge between my program and the Twincat System Manager which forms the bridge between the computer and a PLC via the local network.</p>
  
  <p>I need to read Variables trough this whole chain from the plc to my program.</p>
  
  <p>This is the way I do this:</p>
  
  <pre><code>Public Function adsReadReal(ByVal Variabelenaam As String) As Single
      Dim ds = New TwinCAT.Ads.AdsStream(4 * 8) ' new data stream
      Dim br = New System.IO.BinaryReader(ds) 'new binary
      Dim hVar = New Integer
      Try
          ConState(1) 
          tcclient = New TcAdsClient
          ConState(2)
          tcclient.Connect(Form1.amsAdress, 801) 'connects the tcclient to the PLC
          hVar = tcclient.CreateVariableHandle(Variabelenaam) 'creats a handle for the variable
          tcclient.Read(hVar, ds) 'read it
          ConState(5)
          Return br.ReadSingle() 'convert it from binary to readable for vb
      Catch ex As Exception
          ConState(0)
          PrintEx(ex) 'print out the exception
      finally
          tcclient.Dispose() 'make the object stop being used to prevent a lingering connection
      End Try
      Return False
  End Function
  </code></pre>
  
  <p>Now the program loads a dll called <code>TwinCAT.ADS.dll</code> at the start of the connection module. If the Twincat system manager is running the program ends normally, but when it is not it crashes and gives me this error:</p>
  
  <blockquote>
    <p>System.DllNotFoundException was unhandled<br>
    Message="Kan DLL tcadsdll.dll niet laden: Kan opgegeven module niet vinden. (Uitzondering van HRESULT: 0x8007007E)"<br>
    Source="TwinCAT.Ads"<br>
    TypeName=""<br>
    StackTrace:<br>
      bij TwinCAT.Ads.Internal.TcAdsDllWrapper.TcAdsDll.AdsAmsUnRegisterRouterNotification()<br>
      bij TwinCAT.Ads.Internal.TcAdsDllWrapper.AmsUnRegisterRouterNotification(Boolean
    throwAdsException)<br>
      bij TwinCAT.Ads.Internal.TcLocalSystem.Dispose(Boolean disposing)<br>
      bij TwinCAT.Ads.Internal.TcLocalSystem.Finalize()  </p>
  </blockquote>
  
  <p>which is roughly translated to: </p>
  
  <blockquote>
    <p>Cannot load DLL tcadsdll.dll: Cannot find given module. (Exception at
    HRESULT: 0x8007007E)</p>
  </blockquote>
  
  <p>This is not a dll that I have imported, so it must be from the <code>TwinCAT.ADS.dll</code></p>
  
  <p>How can I prevent the program from throwing this error at me and instead close the program peacefully? I have tried to catch all the exceptions of every dll related operation possible.</p>
  
  <p>Also the source is on Bitbucket. I will make it public on request.</p>
  
  <p>Some links on the official but quite unhandy Beckhoff site:</p>
  
  <p><a href="http://infosys.beckhoff.com/espanol.php?content=../content/1034/tcquickstart/html/tcquickstart_samplevisualbasicnet.htm&amp;id=10449" rel="nofollow">http://infosys.beckhoff.com/espanol.php?content=../content/1034/tcquickstart/html/tcquickstart_samplevisualbasicnet.htm&amp;id=10449</a></p>
  
  <p><strong>Edit:</strong> 
  Apparently using tcclient.dispose() causes the error since the finnaly statement was use instead of just after the try block</p>
  
  <p><strong>Edit:</strong> This currently catches the exception but it does not handle it.</p>
  
  <pre><code>Dim currentDomain As AppDomain = AppDomain.CurrentDomain
  AddHandler currentDomain.UnhandledException, AddressOf MyHandler
  Dim tick As Byte = 0
  
  Sub MyHandler(sender As Object, args As UnhandledExceptionEventArgs)
     Dim ex As Exception = DirectCast(args.ExceptionObject, Exception)
     MsgBox("exception tick" &amp; Str(tick))
     tick = tick + 1
     PrintEx(ex)
  End Sub
  </code></pre>
  
  <p><strong>Edit:</strong>
  The exception isn't caught properly because in vs2008 a couple of errors occurs but the tick appears after I press F5 (continue)</p>
  
  <p>When the program is run directly, I only see 1 Tick. Then windows gives an error.</p>