处理DLL未找到异常

时间:2013-10-15 16:11:01

标签: vb.net dll exception-handling import

我目前的项目运作良好,所以像任何理智的人一样,我试图故意打破它。一种可能性是某些资源可能会丢失。当我忽略在运行文件夹中放入一个dll时,我的应用程序崩溃了。

是否可以“优雅地”处理因资源缺失而导致的异常?

我的一个类导入了一个引用“TcAdsDll.dll”的资源。

....
Imports Okuma.EthernetIO
....

在该类中,我能够捕获尝试使用此资源时生成的异常:

    Try
        Dim objAdsStateInfo As TwinCAT.Ads.StateInfo = Nothing
        Try
             'Do a bunch of fun stuff with Ethernet...
        Catch...  
        'catch Ethernet errors              
        End Try
    Catch ex As Exception
    'This catches the exception generated when I try to instantiate an object that uses the dll which is no longer present
    End Try

但是,在我处理此异常后,程序仍然会崩溃。 一旦退出初始化阶段,将加载表单main并且我一直到该事件的end sub。一旦我执行'End Sub'语句(逐行调试),我收到消息:

DllNotFoundException was unhandled
Unable to load 'tcadsdll.dll': The specified module could not be found.
(Exception from HRESULT: 0x8007007E)

我在使用它的资源做任何事情之前添加了代码来检查这个.dll的存在,但是因为它用import语句链接到类中,所以它仍然试图处理它并崩溃。我是否必须重建资源(Okuma.EthernetIO)以包含检查dll文件?或者是否有一种优雅的方式在我的应用程序中轻松实现这一点,我只是不知道?

UPDATE:在跳转到包含导入的类之前检查dll文件是否存在对我有用。它会阻止首先生成异常。然而问题仍然存在:
有没有办法处理dll未找到的异常?

1 个答案:

答案 0 :(得分:0)

你可以"优雅"通过终止程序来处理DLL未找到的异常:

Dim MissingDll as Boolean = False
Try
    'Do a bunch of fun stuff with Ethernet...
Catch ex As System.DllNotFoundException
    MissingDll = True
    MsgBox("Missing DLL", , "Fatal Error")
    Application.Exit()
End Try

在你的关机代码中,使用MissingDll来避免调用其他也会导致" DllNotFoundException未处理的函数"错误:

If Not MissingDll Then EthernetIO.Close()  ' something like this
相关问题