忽略 C# 中的异常
- 作者: 娶姣姣誓爱一生
- 来源: 51数据库
- 2023-02-08
问题描述
有没有更好的方法来忽略 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#通过fleck实现wss协议的WebSocket多人Web实时聊天(附源码)
- 团队城市未满足要求:MSBuildTools12.0_x86_Path 存在
- 使用 MSBuild.exe 在发布模式下构建 C# 解决方案
- 当我发布 Web 应用程序时,AfterPublish 脚本不运行
- 构建时 T4 转换的产品仅在下一个构建中使用
- ASP.NET Core Application (.NET Framework) for Windows x64 only error in project.assets.json
- 新的 .csproj 格式 - 如何将整个目录指定为“链接文件"到子目录?
- 如何将条件编译符号(DefineConstants)传递给 msbuild
- MSBuild 支持 Visual Studio 2017 RTM 中的 T4 模板
- NuGet 包还原找不到包,没有源
