出现异常时应该如何移动文件?
要求: 发生错误(引发异常)时,应将正在处理的文件移动到包含错误的文件的文件夹(app.config 设置)。
问题: 我处理此问题的唯一方法是在主 Try/Catch 内部嵌套一个 Try/Catch 来尝试移动文件,这样如果移动失败,则会引发另一个异常。 我知道我可以尽最大努力确保该目录存在,并授予权限,但由于它是一个网络驱动器......我只知道在某些时候肯定会发生错误。
例子
Try
(Do Some Logic, but an error happens)
Catch ex As Exception
Try
(Attempt to move file)
Catch exinner as Exception
Throw New Exception("Cannot move file to Error Directory", innerex)
End Try
(Raise Error Event for logging by form/batch app)
End Try
事实上,结果比我想象的更可怕。
现在我知道我做错了。 我应该如何真正尝试处理 catch 中可能发生的错误,以便我仍然可以移动文件并尝试调用我的事件?
The requirement:
On an error (thrown exception), the file being processed should be moved to the folder for files with errors (app.config setting).
The problem:
The only way that I can of handling this is to have a nested Try/Catch inside of the main Try/Catch to try to move the file, that way if the move fails, another exception is thrown. I know that I can do my best to make sure the directory exists, rights are given, but since it is a network drive... I just know an error is bound to happen at some point.
Example
Try
(Do Some Logic, but an error happens)
Catch ex As Exception
Try
(Attempt to move file)
Catch exinner as Exception
Throw New Exception("Cannot move file to Error Directory", innerex)
End Try
(Raise Error Event for logging by form/batch app)
End Try
Actually that came out even more horrible than what I was thinking it would look like.
Now I know I am doing something wrong. How should I really be trying to handle a possible error occuring in the catch, so that I can still move files and try to call my event?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这一切对我来说看起来都很好。 在 catch 中包含 try catch 块是完全合理的。 您可以检查您提到的所有内容,但网络始终有可能出现故障,或者您根本无法写入该文件。 之后你做什么取决于你。 错误消息和暂停处理似乎是合理的。
That all looks good to me. It is perfectly reasonable to have try catch blocks inside a catch. You can check all the things you mentioned but there is always the possibility that the network will go down or you just plain won't be able to write that file. What you do after that is up to you. An error message and pausing processing seems reasonable.
这正是仅使用异常时的做法。 您可能会考虑使用标志,但这也不是更好:
没有那么好......
That is exactly how you'd do it when using Exceptions only. You might consider using flags, but that isn't better either:
Not that much better...