如何处理异常System.ArgumentException

时间:2016-03-22 07:37:42

标签: .net vb.net exception exception-handling try-catch

我在我的应用程序中使用此代码来管理文件夹:

Dim appBasePath As String = Application.StartupPath() 
Dim appPath As String = appBasePath & "\user"   
Private WithEvents FSW As New IO.FileSystemWatcher(appPath)

但是如果路径不存在,则应用程序会抛出此异常:

Exception thrown: 'System.ArgumentException' in System.dll

Additional information: The directory name c:\program\user is invalid.

而且:

An exception of type 'System.ArgumentException' occurred in System.dll but was not handled in user code

Additional information: The directory name c:\program\user is invalid.

我该如何处理这个例外?

1 个答案:

答案 0 :(得分:0)

处理异常的一种方法是在方法块中实例化对象,然后可以编写try / catch块。

一个例子:

Imports System.IO

Public Class Form1 : Inherits Form

    Dim appBasePath As String = Application.StartupPath()
    Dim appPath As String = appBasePath & "\user"

    Friend WithEvents Fsw As FileSystemWatcher

    Public Sub New()

        ' This call is required by the designer.
        MyClass.InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        Try
            Me.Fsw = New FileSystemWatcher(appPath)

        Catch ex As ArgumentException When (Not Directory.Exists(appPath))
        ' ...

        Catch ex As Exception
        ' ...

        End Try

    End Sub

End Class