我有一个有趣的问题,在应用程序关闭期间,try/catch block 在堆栈中似乎被忽略了。
我没有工作测试项目(由于截止日期,否则我会完全尝试重现),但请考虑以下代码片段。
class IndexNotFoundException : Exception { }
public static string RunAndPossiblyThrow(int index, bool doThrow)
{
try
{
return Run(index);
}
catch(IndexNotFoundException e)
{
if(doThrow)
throw;
}
return "";
}
public static string Run(int index)
{
if(_store.Contains(index))
return _store[index];
throw new IndexNotFoundException ();
}
public static string RunAndIgnoreThrow(int index)
{
try
{
return Run(index);
}
catch(IndexNotFoundException e)
{
}
return "";
}
在运行时,这种模式非常有效。我们获得了对依赖程序控制异常的代码的遗留支持(坏),我们继续前进并慢慢删除用于程序控制的异常。
但是,当关闭我们的 UI 时,我们会看到从“Run”抛出的异常,即使对于“RunAndPossiblyThrow”的所有当前使用“doThrow”都是假的。我什至通过将代码修改为看起来像“RunAndIgnoreThrow”来验证这一点,我仍然会在 UI 关闭后遇到崩溃。
先生。 Eric Lippert,我每天都看你的博客,我很乐意听到它是一些已知的错误,我不会发疯。
编辑 这是多线程的,我已经验证所有对象在访问时都没有被修改
编辑 明确显示异常是我们的
编辑 忘了说,这是在关闭时,不幸的是 visual studio 无法直接捕捉到崩溃。它很可能在 UI 线程以外的线程上崩溃,一旦主线程关闭,它就会关闭。我只能通过重复运行和关闭应用程序来调试它,打开任务管理器,“创建转储文件”并查看 Windbg 中产生的 400+mb 困惑。 Win7 64位供引用。确保这对您有意义。
编辑
关闭时的以下代码仍然显示相同的异常。
class IndexNotFoundException : Exception { }
public static string RunAndPossiblyThrow(int index, bool doThrow)
{
try
{
return Run(index);
}
catch
{
}
return "";
}
public static string Run(int index)
{
if(_store.Contains(index))
return _store[index];
throw new IndexNotFoundException ();
}
唯一好像去掉异常的就是直接
class IndexNotFoundException : Exception { }
public static string RunAndPossiblyThrow(int index, bool doThrow)
{
try
{
return Run(index);
}
catch
{
}
return "";
}
public static string Run(int index)
{
if(_store.Contains(index))
return _store[index];
return "";
}
当然异常(exception)已经消失了,但我对发疯的恐惧仍然存在。
编辑
情况变得更糟了...这仍然会崩溃...
class IndexNotFoundException : Exception { }
public static string RunAndPossiblyThrow(int index, bool doThrow)
{
try
{
throw new IndexNotFoundException();
}
catch
{
}
return "";
}
编辑 我有一种明显的感觉,这将使我无处可去。除了奇怪的行为之外,我还可以注意到,在上述情况下的 UI 执行期间,try catch 被忠实地执行。我的 UI 没有崩溃,而且里面全是空字符串。但是,一旦我开始关闭 UI,崩溃就会自行显现,并且 try catch 不再阻止异常。
编辑 & 最终 显然转储文件在其中列出了最近的第一次机会异常。我通过创建一个新项目来验证这一点,该项目将一个 try catch 放入并睡了 10 秒。在等待期间,我得到了 .dmp 文件,果然,我完全捕获的异常出现了。
我会为有用的答案标出一些要点,但不幸的是,仍然没有韵律或我的代码崩溃的原因......
最佳答案
添加一个异常作为额外的捕获。我认为您遇到了 ApplicationException 以外的其他异常,这就是使您的应用程序崩溃的异常。
关于c# - 什么时候 try catch 不是 try catch?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2660450/