[英]Python: variable “tricking” try-exception, but works for if statement
[英]print help text in try-exception in python
在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()
因此,例如,在不带参数的情况下调用此代码时,我想获取“ Generate POSCAR:Some error message”,而不是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'
您可以定义一个新的例外:
class CustomError(Exception): pass
raise CustomError('Generate POSCAR : Some error message')
虽然,您收到的错误与try-except
语句无关。 相反,您的gen_pos()
函数缺少参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.