消除重复的 try/catch 代码 [英] Eliminating repetitive try/catch code

查看:29
本文介绍了消除重复的 try/catch 代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编写必须一次又一次处理相同异常的代码总是很无聊.

Writing code which has to handle the same exceptions time and time again constantly gets boring.

有没有办法不用try/catch来编写代码,并在方法中添加属性来捕获(和处理)可能发生的各种异常?这听起来像 AOP (Postsharp),这是理想的解决方案吗?

Is there a way to write code, without try/catch, and add attributes to the method to catch (and handle) the various exceptions which may occur? This sounds like AOP (Postsharp), would this be the ideal solution?

因此,我想编写可以指示异常记录、重新抛出等的位置/方式的类,并且它们从属性和任何基类/接口派生.然后重用这些并将它们应用于整个代码中的不同方法.这将大大提高一致性.

So I want to write classes which can dictate where/how an exception is logged, rethrown, etc, and they derive from attributes and any base class/interface. And then re-use these and apply them to different methods throughout the code. This will greatly improve consistency.

谢谢

推荐答案

听起来您确实在寻找 AOP 可以提供的功能.根据您的具体目标,您可以按照 Peter O. 建议的方式,通过编写一些辅助方法,而无需额外开销即可获得许多相同的好处.

It does sound like you're looking for functionality that AOP can provide. Depending on what you're specifically going for, you might be able to get a lot of the same benefits without the extra overhead simply by writing some helper methods, the way Peter O. suggests.

我个人并不觉得我有很多重复的异常处理代码,因为异常是......好吧......例外.它们不应该是正常代码流的一部分,除非需要做一些非常具体的事情来响应特定类型的异常,最好的策略通常是根本不捕捉它们,至少在它们涓涓细流之前到您想要记录它们的高级别.

I personally don't find that I have a lot of repetitive exception handling code due to the fact that Exceptions are... well... exceptional. They shouldn't be part of the normal code flow, and unless there's something very specific that needs to be done in response to a specific type of Exception, the best policy is generally not to catch them at all, at least until they trickle up to a high level where you want to log them.

这篇关于消除重复的 try/catch 代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆