[转帖]Why you can't catch some exceptions

If you've been using .NET (or any previous exception-based languages like JScript or C++) for a while then you are probably used to doing something like this:

try

{

  someObject.MethodThatMightFail()

}

catch (ex)

{

  print("uh, something went wrong")

}

But this doesn't always work, especially when you are writing a library that is called by some code you don't own. Kind of like a VSTO project. The times it doesn't work are when using MethodThatMightFail fails at JIT-time (Just In Time compilation) rather than at run-time. For example, if the assembly containing the type that implements the method can't be loaded, the JITter can't JIT the method in which case your try-catch block will never even execute; instead, the method that called your method will receive an exception (probably a MethodInvocationException or a FileNotFoundException or something similar, possibly with an InnerException containing the reason for failure).

If the calling method is not owned by you -- eg, it is an event handler where the caller is Word or Excel in the VSTO case -- they will receive the exception and will most likely throw it away. Therefore if you want to call a method that may fail for some drastic reason such as the assembly not being installed or a LinkDemand failing, then you should wrap it in your own function:

try

{

  Helper()

}

catch (ex)

{

  print("uh, something went wrong")

}

// Meanwhile, in another part of the code...

function Helper()

{

  someObject.MethodThatMightFail()

}

This is a common problem with the _Startup or Open methods in VSTO projects where customers call into assemblies that either are in the wrong directory or are not trusted, and the problem goes unreported by the host app.

From: http://weblogs.asp.net/ptorr/archive/2004/02/07/69433.aspx

posted @   dudu  阅读(699)  评论(0编辑  收藏  举报
编辑推荐:
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· spring官宣接入deepseek,真的太香了~
点击右上角即可分享
微信分享提示