1

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'
BaRud
  • 3,055
  • 7
  • 41
  • 89
  • The exception that posted has nothing to do with the try-catch. The control has not even reached the `genpos` method yet because you're not calling the method properly (missing argument) – rdas Apr 20 '19 at 08:03
  • never use bare `try except` as they catch any exception, even `SystemExit` or `KeyboardInterrupt` – Jean-François Fabre Apr 20 '19 at 08:08
  • Possible duplicate of [How to print Docstring of python function from inside the function itself?](https://stackoverflow.com/questions/8822701/how-to-print-docstring-of-python-function-from-inside-the-function-itself) – mkrieger1 Apr 20 '19 at 08:11

1 Answers1

0

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.

Alec
  • 8,529
  • 8
  • 37
  • 63