不同风格的程序流程? [英] Different styles of flow of program?
问题描述
我是一个计算机科学学生,因此我不知道。
我最近跟一个刚刚得到一个(java)软件开发人员的朋友聊天。他告诉我,在他的工作中有一个真正有C ++经验的人,但不幸的是每次他在java中编写代码时,他都使用try-catch来控制程序的流程。根据我的朋友,这是一个错误的风格在Java。这是真的?在C ++和Java之间使用try-catch(-finally在java中)有什么区别(如果有的话)?
使用try-catch控制程序的流程在任何地方都是错误的...异常处理是它说的是:
情况的处理。当然,每个规则都有十几个必要偏差的反例,
当您预期在正常操作环境中抛出某些异常,并且您做出逻辑决策时,会使用异常来控制程序的流程
例如以伪代码控制程序流程:
try {
pre>
写入更新到文件
} catch(IOException){
写入更新到备用文件
}
在这种情况下,最好在盲目执行写入之前实际测试路径的存在。
异常处理的一个很好的用法:(伪代码)
try {
do stuff
} catch(OutOfMemoryException){
正常失败别的,以实现相同的结果)
}
I am a computer science student therefore I do not know that much.
I was recently talking with a friend who just got a job as a (java) software developer. He told me that in his job there is a guy who is really experienced in C++, but unfortunately every time he writes code in java, he is using the try-catch to control the flow of the program. According to my friend this is a wrong style in Java. Is this true? What are the differences (if any) in using try-catch(-finally in java) between C++ and Java?
解决方案Using try-catch to control the flow of the program is wrong anywhere... Exception handling is what it says it is: Handling of exceptional circumstances.
Of course for every rule there are a dozen counter-examples of necessary deviations, but generally speaking: Don't control program flow with exceptions.
Using exceptions for controlling the flow of a program occurs when you anticipate certain exceptions being thrown in a normal operating environment, and you make logical decisions based on those exceptions.
For example controlling program flow in pseudo code:
try { write update to file } catch (IOException) { write update to alternate file }
In this case it would be better to actually test for path existence before blindly performing the write.
I removed the permission checking notes because it's a bad example
A good usage of exception handling: (pseudo code again)
try { do stuff } catch(OutOfMemoryException) { fail gracefully (don't try and do something else to achieve the same result) }
这篇关于不同风格的程序流程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!