抑制某些类型异常的属性?
我可以使用附加到方法定义的任何属性来抑制源自该方法的某种类型的任何异常吗?例如
[SuppressException(typeof(TimeoutException))]
public void TroubleMethod()
{
}
,那么当存在TimeoutException
时,它不会抛出TroubleMethod
之外?
Is there any attribute that I can use, attached to the method definition, that will suppress any exceptions of a certain type originating in that method? e.g.
[SuppressException(typeof(TimeoutException))]
public void TroubleMethod()
{
}
So when there is a TimeoutException
, it won't throw outside of TroubleMethod
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以在整个方法中使用异常处理:
不过,我认为不存在执行您所描述的操作的属性。如果您希望调试器单步执行您的方法,您始终可以使用
[System.Diagnostics.DebuggerStepThrough()]
,但至于抑制异常,我认为这是不可能的。You can use exception handling around the entire method:
I don't think an attribute that does what you describe exists, though. If you want the debugger to step through your method, you can always use
[System.Diagnostics.DebuggerStepThrough()]
, but as for suppressing exceptions, I don't think that's possible.您可以使用 PostSharp 进行一些棘手的检测来添加此类属性。
You can use PostSharp to do some tricky instrumentation to add such attribute.
如果您确实想这样做,您可以使用以下方法更接近类似属性的语法:
If you really want to do this, you can get a bit closer to your attribute-like syntax with:
据我所知,但你总是可以这样做:
在几乎所有情况下都是一个坏主意,尽管有时可以接受(很少见)。请确保为未来的维护者(包括您)留下评论。
Not that I am aware of, but you can always do this:
A bad idea in almost all circumstances, though sometimes acceptable (rare). Just make sure to leave a comment for future maintainers (this includes you).
您可以使用 try-catch 捕获异常并忽略它,或者更好的是您可以响应该异常
查看参考
you could use try-catch to catch the exeptions and just ignore it or better you could respond to that exeption
check out the reference