try / catch语句使用公约(S) [英] Try/Catch Use Convention(s)

查看:99
本文介绍了try / catch语句使用公约(S)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是明显需要的位置(如获取特定的用户输入)的外面的try / catch公约?虽然代码重用的背后是OOP一个重要思想,就是它期望每个(例如)数组访问应该有一个try / catch?它是主要设计师的什么可以抛出一个异常,这应该是良好的监管不够方案的部分永远不会抛出异常的决定呢?

What is the convention for Try/Catch outside of obviously needed locations(such as getting specific user input)? While code re-use is an important idea behind OOP, is it expected that each (example) array access should have a try/catch? Is it primarily the designer's decision of what can throw an exception, and those parts of the program that should be well regulated enough to never throw an exception?

防爆。扑克牌数组是的,应该永远是52卡。没有的try / catch是必要的。
或因为数组越界异常可能会导致运行时错误,并在甲板上可能在稍后的日期与王牌被用来添加,然后把它放在现在呢?

Ex. An array of playing cards is, and should always be, 52 cards. No try/catch is necessary. Or since an array out of bounds exception could cause a run-time error, and the deck could be used at a later date with jokers added, then put it in now?

推荐答案

您的例子是有点过。

假设你有52个元素的数组,正确的方法处理这个是测试你的指数是数组的边界之内,甚至试图访问它。这远远不是简单地包装在一个try代码越好..赶在了那里。

Assuming you have an array of 52 elements, the correct way of handling this is to test that your index is within the bounds of the array before even attempting to access it. This is far better than simply wrapping the code in a try .. catch in there.

尝试捕捉是有帮助拯救我们自己。如果一个给定的方法是正确编码则很少有使用它们的理由。通过适当我的意思是您验证输入的预期范围之内,你已经测试不够了解,该代码不会除掉了。当然,非常小的例子包括诸如SqlConnection对象调用非托管资源。

Try Catch is there to help save us from ourselves. If a given method is coded properly then there is very little reason to use them. By properly I mean that you verify your inputs are within the ranges expected and you've tested enough to know that the code won't "except" out. Of course, an example of "very little" include calls to unmanaged resources such as the SqlConnection object.

的一点是,这是一个拐杖是最后的努力挽救可用的东西出特定的代码块的执行。

Point is, it's a crutch that is a last ditch effort to salvage something usable out of that particular code blocks execution.

如果,但是,没有什么字面上可以做有关异常的话,我会说你唯一的选择是忽略它,让它泡了还是抓,登录并重新抛出。

If, however, there is literally nothing that can be done about the exception then I'd say your only choices are to ignore it and let it bubble up or catch, log and rethrow.

这篇关于try / catch语句使用公约(S)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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