[转帖]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

转载于:https://www.cnblogs.com/dudu/archive/2004/02/08/1026.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值