捕捉并吃掉异常
我有以下抛出
try
{
fileInfo.CopyTo(destination, true);
}
catch (IOException ioex)
{
}
Log4net log 的代码:
35552|384|1|ERROR| at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
我需要吃掉这个异常并且不记录它。我需要抑制这个错误消息。
怎么做呢?
I have the following code that throws
try
{
fileInfo.CopyTo(destination, true);
}
catch (IOException ioex)
{
}
Log4net log :
35552|384|1|ERROR| at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
I need to eat this exception and not log it. I need to supress this error message.
How to do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我怀疑您需要查看 Log4net,看看是否有一种方法可以只记录未处理的异常(如果这是需要的),或者有一种方法可以告诉它忽略特定位置的异常。
为什么你特别想隐藏这个?如果是因为这种情况经常发生并用无用的信息填充日志,那么您可能需要在调用 CopyTo 之前进行一些验证,以确保它有合理的机会成功(即路径有效,文件存在等)。这也将首先减少抛出异常的数量。异常在性能方面有些昂贵,因此如果可以的话,您将希望防止它们发生。
正如我在对该问题的评论中提到的,您不能完全删除异常处理,因为总是有可能另一个程序在检查文件是否存在和实际调用
CopyTo
之间删除了该文件,但它应该是这是极其罕见的现象。如果这种情况不经常发生和/或您已经在进行检查,那么偶尔记录一下有什么害处?
I suspect you'll need to look at Log4net to see if there's a way to either only log unhandled exceptions (if that's what's desired) or a way to tell it to ignore an exception in a specific place.
Why specifically do you want to hide this though? If it's because this happens a lot and fills up the log with useless info then you may want to do some validation before calling
CopyTo
to make sure there's a reasonable chance it'll succeed (i.e. path is valid, file exists, etc). This will also cut down on the number of exceptions throw in the first place. Exceptions are somewhat expensive performance-wise so you'll want to prevent them from occuring if you can.As I mentioned in a comment on the question, you can't remove the exception handling entirely because there's always a chance another program deleted the file in between checking it's existing and actually calling
CopyTo
, but it should be an extremely rare occurrence.If this isn't happening frequently and/or you're already doing checks, what harm is there in having this occasionally logged?
将函数调用放在 try/catch 中,捕获有问题的异常,并提供一个空块:请注意,捕获异常(而不是正确的子类)是可怕的做法。好吧,在我写这篇文章时,这个问题已经被秘密编辑了。我根本不知道 log4net 记录通过 CLR 的所有异常。我很快就会删除它,但现在我将其保留,以备进一步评论。
Put the function call in a try/catch, catch the exception in question, and supply an empty block:Note that catching Exception (rather than the proper subclass) is TERRIBLE practice.Okay, the question was edited stealthily as I wrote this. I have no clue about log4net logging all exceptions that pass through the CLR at all. I'll be deleting this shortly, but for now I'm leaving it up in case of further comment.