Ignore Exception in C#(忽略 C# 中的异常)
问题描述
有没有更好的方法来忽略 C# 中的异常,而不是将其放在 try catch 块中并且在 catch 中什么也不做?我发现这种语法很麻烦.对于代码块,我不能简单地标记"它,以便运行时知道要忽略哪些异常吗?
Is there a better way to ignore an exception in C# than putting it up in a try catch block and doing nothing in catch? I find this syntax to be cumbersome. For a codeblock, can't I simply "tag" it in such a way so as runtime knows which exceptions to neglect?
推荐答案
我不认为有什么技巧可以避免异常,但是你可以使用下面的代码片段:
I don't think there is a trick to avoid exception but you can use the following code snippet:
public void IgnoreExceptions(Action act)
{
try
{
act.Invoke();
}
catch { }
}
使用方法如下:
IgnoreExceptions(() => foo());
另一种解决方案是使用 AOP(面向方面编程) - 有一个名为 PostSharp 的工具可以让您创建一个可以捕获特定程序集/类/方法中所有异常的属性,这更接近您要查找的内容.
Another solution is to use AOP (Aspect Oriented Programming) - there's a tool called PostSharp which enables you to create an attribute that would catch all exceptions in specific assembly/class/method, which is closer to what you're looking for.
这篇关于忽略 C# 中的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:忽略 C# 中的异常


基础教程推荐
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01