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

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

问题描述

不得不一次又一次地处理相同异常的编写代码不断变得无聊.

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

是否有一种无需try/catch即可编写代码的方法,并且可以向该方法添加属性以捕获(并处理)可能发生的各种异常?听起来像AOP(后锐化),这是理想的解决方案吗?

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.

我个人没有发现我有很多重复的异常处理代码,这是因为Exceptions是...好...非常好.它们不应成为常规代码流的一部分,除非需要针对特定​​类型的Exception进行某些非常具体的操作,否则最佳策略通常是根本不捕获它们,至少直到它们滴入为止到您要记录它们的较高级别.

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天全站免登陆