rud*_*ter 27 python exception-handling
我有这个尝试/除了代码:
document = raw_input ('Your document name is ')
try:
with open(document, 'r') as a:
for element in a:
print element
except:
print document, 'does not exist'
Run Code Online (Sandbox Code Playgroud)
打印"[filename]不存在"后如何退出程序? break并且pass显然不起作用,我不想有任何崩溃错误,因此sys.exit不是一个选项.
请忽略这try部分 - 它只是一个假人.
Cha*_*guy 31
使用sys.exit:
import sys
try:
# do something
except Exception, e:
print >> sys.stderr, "does not exist"
print >> sys.stderr, "Exception: %s" % str(e)
sys.exit(1)
Run Code Online (Sandbox Code Playgroud)
一个好的做法是打印出现的异常,以便以后可以进行调试.
您还可以使用traceback模块打印堆栈跟踪.
请注意,您在sys.exit中返回的int将是程序的返回码.要查看程序返回的退出代码(这将为您提供有关已发生的事件和可自动化的信息),您可以执行以下操作:
echo $?
Run Code Online (Sandbox Code Playgroud)
Gre*_*ill 10
运用
sys.exit(1)
Run Code Online (Sandbox Code Playgroud)
这不是崩溃错误,退出程序是一种非常正常的方法.退出代码1是一个约定,意味着出错(在成功运行的情况下,您将返回0).
您还可以将代码放在函数中并发出返回.您可以将其称为main,您可以从脚本中调用它.
def main():
document = raw_input ('Your document name is ')
try:
with open(document, 'r') as a:
for element in a:
print element
except:
print document, 'does not exist'
return
if __name__ == "__main__":
main()
Run Code Online (Sandbox Code Playgroud)
如果您if在 a 中使用语句try,则将需要多个语句sys.exit()才能实际退出程序。
例如,您在调用某个文件的执行时正在解析参数,例如$./do_instructions.py 821:
import sys
# index number 1 is used to pass a set of instructions to parse
# allowed values are integer numbers from 1 to 4, maximum number of instructions is 3
arg_vector = "821" # <- pretending to be an example of sys.argv[1]
if len(arg_vector) > 3:
sys.exit(2) # <- this will take you out, but the following needs an extra step.
# for an invalid input (8).
for i in arg_vector:
# to validate that only numbers are passed as args.
try:
int(i) # <- 8 is valid so far
# value (8) is not valid, since is greater than 4
if (int(i) == 0) or (int(i) > 4):
print("Values must be 1-4")
# the following call does not takes you out from the program,
# but rise the SystemExit exception.
sys.exit(2)
except SystemExit: # <- needed to catch the previous as the first evaluation
# The following parameter "2" is just for this example
sys.exit(2) # <- needed to actually interrupt the execution of the program/script.
# if there is no "except SystemExit:", the following will be executed when the
# previous "if" statement evaluates to True and the sys.exit(2) is called.
#
# and the "print("Only num...") function will be called, even when the intention
# of it is to advice the *user* to use only numbers, since 8 is a number this
# shouldn't be executed.
except:
print("Only numbers are allowed.")
sys.exit(2)
Run Code Online (Sandbox Code Playgroud)
否则,您需要为每次评估使用一个try- except块。
重新加注吧.它对开发人员更友好
document = raw_input ('Your document name is ')
try:
with open(document, 'r') as a:
for element in a:
print element
except:
print document, 'does not exist'
raise
Run Code Online (Sandbox Code Playgroud)
检查蟒蛇文件中关于重新加注错误引发异常部分except.
| 归档时间: |
|
| 查看次数: |
67410 次 |
| 最近记录: |