本文介绍了岂不是更好使用保护条款或捕捉异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 是它更好地防止异常与保护条款或捕获异常? 有一个最好的做法? ? Pro和两种方法的缺点 例如更好这样的: 试 {参数= myArray的[3]; } 赶上(IndexOutOfRangeException E) {做某事} 或这样的: 如果(myArray.Length 4;) {做某事} ,否则 {参数= myArray的[3]; } 感谢大家的答案:) 解决方案 有只在愚蠢的异常的情况下,后者的缺点。它们是: 异常是令人难以置信的昂贵的对比测试 例外旨在模拟的非常罕见的控制流的情况;如果有可能访问一个索引超出范围的正常的话不写的例外的处理程序。 例外报告第一机会例外听众的即使异常被处理的。许多系统 - ASP,例如 - 听第一次机会异常,记录所有的人,并把产生他们中的很多作为组件的车的,因为的他们的。 (我曾经在ASP一个共同的代码路径引入故意第一次机会异常,一天以后男孩没听说这件事。马车子系统的测试都疯狂了。) 有一些例外,我称之为愚蠢的例外 - 空取消引用,指数超出范围,等等 - 因为他们是如此容易避免,并指出这样的故障很明显的危险,他们应该的总是的被视为致命错误,并且的从不的处理(除非处理程序正在关闭的过程之前记录它们。)不要处理错误,的消除错误的。 最后,你应该看过我对这个问题的文章。 http://ericlippert.com/2008/09/10/vexing-exceptions/ is it better to prevent exception with a guard clause or catch the exception?There is a best practice?Pro and cons of the two methodologies?For example is better this:try{ param=myArray[3];}catch (IndexOutOfRangeException e){ do something...}or this:if(myArray.Length < 4){ do something...}else{ param=myArray[3];}Thank you all for the answers :) 解决方案 In the case of "boneheaded" exceptions like index out of range, always the former.In the case of "exogenous" exceptions, always the latter.There are only cons of the latter in the case of boneheaded exceptions. They are:Exceptions are incredibly expensive compared to tests.Exceptions are intended to model exceptionally rare control flow situations; if potentially accessing an index out of range is normal then don't write an exception handler.Exceptions are reported as "first chance" exceptions to listeners even if the exception is handled. Many systems -- ASP, for example -- listen for first chance exceptions, log all of them, and treat components that produce a lot of them as buggy, because they are. (I once introduced a deliberate first-chance exception in a common code path in ASP and a day later boy did I hear about it. The buggy-subsystem tests went crazy.)There are some exceptions that I call the "boneheaded" exceptions -- null dereference, index out of range, and so on -- that because they are so easy to avoid and indicate failures so obviously dangerous that they should always be treated as fatal bugs and never handled (unless the "handler" is logging them before shutting down the process.) Don't handle the bug, eliminate the bug. Finally, you should read my article on this subject.http://ericlippert.com/2008/09/10/vexing-exceptions/ 这篇关于岂不是更好使用保护条款或捕捉异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-16 06:42