【发布时间】:2019-09-10 07:04:28
【问题描述】:
在 python 的 try-exception 块中,如下所示,我希望打印我的帮助消息,而不是 python 自己的错误消息。这可能吗?
def genpos(a):
''' Generate POSCAR :
Some error message'''
try:
tposcar = aio.read(os.path.join(root,"nPOSCAR"))
cell = (tposcar.get_cell())
cell[0][0] = a
cell[1][1] = math.sqrt(3)*float(a)
tposcar.set_cell(cell, scale_atoms=True)
aio.write("POSCAR", tposcar, direct=True)
except:
help(genpos)
sys.exit()
所以,比如说,当这个代码在没有参数的情况下被调用时,我想得到“生成 POSCAR:一些错误消息”而不是 python 的 Traceback(最近一次调用最后一次):
File "submit.py", line 41, in <module>
main()
File "submit.py", line 36, in __init__
ase_mod.genpos()
TypeError: genpos() missing 1 required positional argument: 'a'
【问题讨论】:
-
发布的异常与try-catch无关。控件甚至还没有到达
genpos方法,因为您没有正确调用该方法(缺少参数) -
永远不要使用裸露的
try except,因为它们会捕获任何异常,即使是SystemExit或KeyboardInterrupt
标签: python error-handling try-except