FCL 是否已经有异常意味着方法执行失败?

发布于 2024-07-14 19:41:22 字数 270 浏览 7 评论 0原文

我有自己的异常,它在方法执行失败时抛出(在我的例子中是 p/invoke)。

public PInvokeException(string methodName)
: base(String.Format(CultureInfo.CurrentCulture,
"An error occured while external method '{0}' call",
methodName)) { }

但我想用已经存在的替换它。 整柜有类似的东西吗?

I have my own exception, which been throwing on execution fail of a method (p/invoke in my case).

public PInvokeException(string methodName)
: base(String.Format(CultureInfo.CurrentCulture,
"An error occured while external method '{0}' call",
methodName)) { }

But I want to replace it with already existing. Is there in FCL something like that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

情定在深秋 2024-07-21 19:41:23

有一个: Win32Exception

如果您抛出异常的方法是 .Net 方法,您应该使用自定义异常(或现有异常,具体取决于发生的情况)。

如果您代表调用您的方法的人调用一个方法(或与反射有关的事情 - 但 MethodInfo.Invoke 无论如何都会这样做),例如:

public void DoIt(Action action) { action(); }

您应该使用 TargetInvocalException 异常。

如果无法处理异常,请重新抛出它,或忽略它。

There is one: Win32Exception.

If the method you are throwing an exception from is a .Net method you should be using a custom exception (or an existing one, depending on what happened).

If you call a method on behalf of the person calling your method (or something to do with reflection - but MethodInfo.Invoke does it anyway), for example:

public void DoIt(Action action) { action(); }

You should use the TargetInvocationException exception.

If you can't handle the exception, rethrow it, or ignore it.

独行侠 2024-07-21 19:41:23

System.Runtime.InteropServices.ExternalException 怎么样?

How about System.Runtime.InteropServices.ExternalException?

征﹌骨岁月お 2024-07-21 19:41:22

您的调用者是否会根据您是否抛出 PInvokeException 与 InvalidOperationException 来采取不同的操作? 如果是这样,则创建一个自定义 PInvokeException。 否则使用 InvalidOperationException 和明确的错误消息。

请参阅如何设计异常层次结构

Is your caller going to take different actions based on whether you throw a PInvokeException vs. an InvalidOperationException? If so, then create a custom PInvokeException. Otherwise use InvalidOperationException and a clear error message.

See How to design Exception Hierarchies.

惯饮孤独 2024-07-21 19:41:22

BCL 中没有专门用于 PInvoke 调用的内容。 最接近的是 Marshal.GetExceptionForHR 和 Marshal.GetHRForLastWin32Error。 每当 PInvoke 调用失败时,您可以结合使用这两个函数来引发相应的异常。

前任:

throw Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error());

There is nothing that is dedicated to PInvoke calls in the BCL. The closest that exists is Marshal.GetExceptionForHR and Marshal.GetHRForLastWin32Error. You can use the combination of these two functions to throw the appropriate exception whenever a PInvoke call fails.

Ex:

throw Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error());
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文