Ignore Exception at a certain Location while debugging?

时间:2019-01-18 18:34:00

标签: c# debugging exception

Our Application is moving some files it requires to run during startup.

The application takes care (on shutdown) to properly stop every process using this files.

However, if the application crashes / or you just hit "stop" in VS on Debugging - some executables might still be running.

So, if you quickly restart the application, it might happen, that the copy-attempt is failing, due to the file is still in use.

For such a case, we just ignore the failed copy attempt - or more exactly: the failed deletion attempt which should make sure, that the latest version is available:

foreach(String entry in contents)
{
    if (System.IO.File.Exists(entry))
    {
        try
        {
            System.IO.File.Delete(entry);
        }catch (Exception e)
        {
            //ignore during this startup.
        }
    }
}

Now, this works perfectly fine, as there is a version of the file available for usage and the production version just ignores the exception.

The annoying Problem is, that the Debugger "breaks" everytime, this error happens.

  • We don't want to generally "ignore" any System.IO.IOException thrown while debugging.
  • We tried to annotate the method in Question with [System.Diagnostics.DebuggerStepThrough()] which works, but causes the exception to be catched at the callers position.

So, is there a way to ignore "some" exceptions raised at a certain line of code, even if general "breaking" for that kind is enabled?

Some #if (DEBUG)-Directives which will avoid the exception to be catched at this particular line of code?

Something like:

foreach(String entry in contents)
{
    if (System.IO.File.Exists(entry))
    {
        try
        {
#if (DEBUG:NoThrow)
            System.IO.File.Delete(entry);
#endif
        }catch (Exception e)
        {
            //ignore during this startup.
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我仍然对答案感兴趣,因为它有“许多”用例。

为了节省时间,我们使用了以下“解决方法”:检查是否已在3分钟内访问了该文件-请勿尝试删除它。 (对于调试模式!)

请记住,实际的问题仅与“调试器”有关,而与生产无关,对于特定的代码行,可以很容易地捕获(并忽略)异常。

如果在此代码行中可以轻松地忽略异常,我们只是想避免出现“ Debugger-Breaks”。

foreach (String entry in contents)
{
    if (System.IO.File.Exists(entry))
    {
        try {
#if (DEBUG)
            FileInfo fi = new FileInfo(entry);
            if (fi.LastAccessTime < DateTime.Now.AddMinutes(-3))
            {
#endif
                System.IO.File.Delete(entry);
#if (DEBUG)
            }
#endif
        }
        catch (Exception e)
        {
            //ignore
        }
    }
}

这不是解决方案,而是一种解决方法,以防您仅在Visual Studio中“停止” Debuggin,从而使此代码行的Debugger-Breaks减少了约99%!