简体   繁体   中英

print help text in try-exception in python

in a try-exception block in python, like shown below, I want my help message to be printed, instead of python's own error message. Is this possible?

 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()

So, say, when this code is called without an argument, I want to get "Generate POSCAR : Some error message" instead of, python's Traceback (most recent call last):

  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'

You can define a new exception:

class CustomError(Exception): pass

raise CustomError('Generate POSCAR : Some error message')

Although, the error you're receiving has nothing to do with the try-except statement. Instead, your gen_pos() function is missing an argument.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM