【问题标题】:How to handle exception System.ArgumentException如何处理异常 System.ArgumentException
【发布时间】:2016-07-08 23:57:02
【问题描述】:

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

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.

我该如何处理这个异常?

【问题讨论】:

  • 视情况而定,您可能不应该这样做。只需验证您使用的数据,如果 Directory.Exists(appPath) 返回 false 那么接下来不会发生任何好事。告诉用户。
  • 问题是如果找不到路径,应用程序会崩溃...如何向用户显示此消息:MsgBox("Path not found.", MsgBoxStyle.Critical, "Error") 并关闭应用程序?也许在表单加载事件中.. 我不知道.. 我对此很陌生.. 我如何验证此语句中的数据? Private WithEvents FSW As New IO.FileSystemWatcher(appPath)
  • 如果您不告诉我们 appPath 的来源,您将无法获得好的建议。它的值是如何设定的?显示更多代码。
  • @Hans Passant appPath 来自这里:Dim appBasePath As String = Application.StartupPath() Dim appPath As String = appBasePath & "\user"
  • 发布真实异常消息。

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


【解决方案1】:

处理异常的一种方法是在方法块内实例化对象,然后您可以在其中编写 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

【讨论】:

    猜你喜欢
    • 2015-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多