在python的try-exception中打印帮助文本

时间:2019-04-20 08:00:08

标签: python error-handling try-except

在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 追溯(最近一次通话):

  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'

1 个答案:

答案 0 :(得分:0)

您可以define a new exception:

try/catch

尽管,您收到的错误与do { let result = try JSONDecoder().decode(Images.self, from: data) } catch { print(error.localizedDescription) } 语句无关。相反,您的class CustomError(Exception): pass raise CustomError('Generate POSCAR : Some error message') 函数缺少参数。