防御性编程和异常处理
前几天,我在考试中遇到了以下理论问题: (a) 解释在处理以下问题时防御性编程的含义 执行过程中可能出现的特殊情况 程序。您可以参考课堂上看到的例子或使用伪 描述为防止某些情况而采取的步骤的代码 例如,在尝试读取文件时发生。 [5 分]
(b) 简要描述异常处理的含义 Java 中的内容以及这与防御性编程有何不同。 [5 分]
我一直认为防御性编程是编程的整个范式,异常处理是其中的一部分。 在考试期间,我写道,在“防御性编程”中,程序员尝试在执行逻辑代码之前找出所有可能的问题,然后从该函数返回错误值(示例0),而在异常处理中,潜在的错误发生并被捕获通过特殊的机制,这些错误被直接解释。对吗?正确答案应该是什么?
A couple days ago, I have following theoretical questions on the exam:
(a) Explain what is meant by defensive programming when dealing with
exceptional circumstances that may occur during the execution of a
program. You may refer to examples seen in class or use pseudo
code to describe the steps taken to prevent certain circumstances
from occurring when trying to read a file for example.
[5 marks]
(b) Briefly describe in general terms what is meant by exception handling
in Java and how this differs from defensive programming.
[5 marks]
I always thought that defensive programming is the whole paradigm of programming and that exception handling is the part of it.
During exam I write that in "defensive programming", programmer try to find out all possible problems before executing the logic code, and later on return error value(example 0) from this function, whereas in exception handling the potential errors occurs and are caught by special mechanism, in which these errors are directly being interpreted. Is it right? What should be correct answers?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对我来说,防御性编程意味着编写代码来处理您认为不会甚至不会发生的情况,因为您相信自己的信念不可靠。
例如(未编译或测试,条款和条件适用):
其中,可以说是防御性功能包括:
并不是每个人都同意空值检查是防御性的。 try-catch 已经到了完全没有意义的程度。
对我来说,防御性编程的严峻考验是你认为防御永远不会被使用。
Defensive programming, to me, means writing code to handle cases that you do not think will, or even can, happen, because you have a belief that your own beliefs are unreliable.
For example (not compiled or tested, terms and conditions apply):
In there, arguably defensive features include:
Not everyone would agree that the null checks are defensive. The try-catch is, to the point of being completely pointless.
For me, the acid test of defensive programming is that you don't think the defence will ever be used.
对我来说,防御性编程是假设最坏的情况:你的用户是完全疯狂的人,你必须保护自己和你的程序免受他们疯狂输入的影响。我相信这句话中蕴藏着很多智慧:
,永远不要忘记您的用户不仅仅是您的客户。如果您负责库 API,您的用户可能是其他部门。在这种情况下,我一生中听到的最尖锐的抱怨之一是:
For me defensive programming is assuming the worst case: that your users are complete crazy people and you must defend yourself and your program from their crazy inputs. I believe there is a lot of wisdom within this quote:
And never forget that your users are not only your clients. If you are responsible of a library API your users might be other department. In that case one of the most stellar complains I ever heard in my life was: