如何确定异常子类型

时间:2017-08-09 14:06:53

标签: vb.net exception-handling

我想知道是否有一种标准方法来确定异常的子类型。例如,对于File.Copy()方法,IOException表示目标文件存在 OR 发生一般I / O错误。还有其他这样的情况。在我的异常处理程序中,如何确定它是什么?我正在检查ex.Message的结尾,查找字符串already exists.,这有效,但看起来非常糟糕且不可靠。

虽然可以检查目标文件上的File.Exists(),但确认覆盖用户是否存在,然后执行File.Copy()这不是原子的,也就是说,在检查和复制之间,条件可能会发生变化,例如,如果某个其他进程创建或将文件复制到目标位置。

编辑: 我已经根据这里的评论更改了代码,但我只是将其回滚并将其发布在此处,以显示我正在做的事情:

        Try
            File.Copy(SrcFile, DstFile, OverWrite)

        Catch ex As DirectoryNotFoundException
            MsgBox(ex.Message)

        Catch ex As FileNotFoundException
            MsgBox("File not found: " & ex.FileName)

        Catch ex As UnauthorizedAccessException
            MsgBox("You do not have write access to the destination.")

        Catch ex As IOException
            ' IOException represents an existing destination file OR a general IO error.
            If SubStr(ex.Message, -15) = "already exists." Then
                OverwriteCheck = MsgBox(
                "Overwrite " & IO.Path.GetFileName(SrcFile) & " in destination directory?",
                MsgBoxStyle.YesNo
                )
                If OverwriteCheck = DialogResult.Yes Then
                    Try
                        File.Copy(SrcFile, DstFile, OverWrite)
                    Catch iex As Exception
                        MsgBox("Unable to copy " & SrcFile & ":" & vbNewLine & iex.Message)
                    End Try
                End If
            Else
                Throw ex
            End If

        Catch ex As ArgumentException
            ' The user left a blank line in the text box. Just skip it.
        End Try

2 个答案:

答案 0 :(得分:3)

这是一个使用FileStreams获取有关您的异常的更详细信息的选项

Sub Main()
    Try
        copyTo("C:\t\output3.txt", "C:\t\output1.txt", True)
    Catch ex As Exception
        Console.WriteLine(ex.Message)
    End Try
    Console.ReadLine()
End Sub

Private Sub copyTo(source As String, destination As String, Optional overwrite As Boolean = False)
   ' raises FileNotFoundException if source doesn't exist
    Using fsSource As New FileStream(source, FileMode.Open, FileAccess.Read, FileShare.None)
        If Not overwrite AndAlso File.Exists(destination) Then
            ' Raises exception when destination file exists and not overwrite
            Throw New Exception(
                String.Format("Destination file '{0}' exists and overwrite is false.", destination))
        Else
            Using fsDestination As New FileStream(destination, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None)
                fsSource.CopyTo(fsDestination)
            End Using
        End If
    End Using
End Sub

这是一个基本的例子,但您可以看到如何区分不同的异常情况,同时在检查文件存在和复制之间具有原子性。

答案 1 :(得分:1)

我相信你在寻找这种模式:

Try
    IO.File.Copy("source", "Dest", True)

Catch exUnAuth As System.UnauthorizedAccessException

Catch exArg As System.ArgumentException

Catch exNotFound As IO.FileNotFoundException

Catch exGeneral As System.Exception

End Try

将特定异常列表放在序列中的第一位。测试的最后一个异常应该是最少的派生。

您应该阅读文档:How to use structured exception handling in Visual Basic .NET or in Visual Basic 2005。是的,这是一个旧的参考,但这表明这是该语言的一部分。