cla*_*aws 3 language-agnostic exception-handling
条件检查:
if denominator == 0:
// do something like informing the user, or skipping this iteration.
else:
result = numerator/denominator
if FileExists('path/to/file'):
// open file read & write.
else:
// do something like informing the user, or skipping this iteration.
Run Code Online (Sandbox Code Playgroud)
异常处理:
try:
result = numerator/denominator
catch (DevidedByZeroException):
//take action
try:
//open file read & write.
catch (FileNotExistsException):
//take action
Run Code Online (Sandbox Code Playgroud)
我经常遇到这样的情况.哪一个去?为什么?
一如既往地依赖.
在我看来,例外应该是例外.
如果您经常期望某些东西可能不起作用,那么您应该进行条件检查.无论是否存在问题,都会一直执行条件检查代码,因此检查不会花费很多时间.
您应该在罕见或不太可能的情况下处理异常处理.那么文件不存在的可能性有多大?
我有一个案例,我想将文件写入网络驱动器,检查UNC共享存在的代码可能需要30秒才能超时,因此您希望在此处使用异常!