【发布时间】:2018-01-17 11:35:07
【问题描述】:
我想知道是否有确定异常子类型的标准方法。例如,对于File.Copy() 方法,IOException 表示目标文件存在或发生了一般 I/O 错误。还有其他类似的情况。在我的异常处理程序中,我如何确定它是哪个?我正在检查ex.Message 的末尾是否有字符串already exists.,它有效,但看起来非常笨拙且不可靠。
虽然可以在目标文件上检查File.Exists(),但如果存在,请与用户确认覆盖,然后执行File.Copy(),这不是原子的,也就是说,在检查和复制之间,可以要更改的条件,例如,如果某个其他进程创建或将文件复制到目标位置。
编辑: 我这里已经根据 cmets 改过代码了,不过我只是回滚了,就贴在这里,只是为了说明我在做什么:
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
【问题讨论】:
-
在您的具体情况下,您应该检查 destFileName 是否存在并且覆盖是否为 false。
-
OK,先用
File.Exists()直接检查,而不是依赖异常?我想我必须这样做。 -
如果可以避免异常,则永远不要将其作为程序逻辑的一部分。
-
啊,我明白了。谢谢你。如果你觉得值得,你能把这一切都放在一个答案中吗?
-
@djv 我只是想到了一些东西:
File.Exists()->File.Copy()不是原子的。嗯,我猜够近了。