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'
3
  • 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) Commented Apr 20, 2019 at 8:03
  • never use bare try except as they catch any exception, even SystemExit or KeyboardInterrupt Commented Apr 20, 2019 at 8:08
  • Possible duplicate of How to print Docstring of python function from inside the function itself? Commented Apr 20, 2019 at 8:11

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Correct. I am trying to print that docstring when I get such mismatch. Can I do that?
You can raise whatever message you want

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.