更新时间:2023-11-22 14:50:46
使用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) }