exception - In Python, how do I print an error message without printing a traceback and close the program when a condition is not met? -
i've seen similar questions 1 none of them address trackback. if have class so
class stop_if_no_then(): def __init__(self, value one, operator, value_two, then, line_or_label, line_number): self._firstvalue = value_one self._secondvalue = value_two self._operator = operator self._gohere = line_or_label self._then = self._line_number = line_number def execute(self, otherclass): "code comparing first 2 values , making changes etc"
what want execute method able if self._then not equal string "then" (in allcaps) want raise custom error message , terminate whole program while not showing traceback.
if error encountered thing should print out (i'm using 3 example, formatting not problem) this.
`syntax error (line 3): no -then- present in statement.`
i'm not picky being exception class object, there's no issue in aspect. since using in while loop, simple if, elif repeats message on , on (because not closing loop). have seen sys.exit() prints out giant block of red text, unless not using correctly. don't want catch exception in loop because there other classes in same module in need implement this.
you can use try:
, except exception inst:
give error message in variable named inst , can print out arguments on error inst.args
. try printing out , seeing happens, , item in inst.args
1 looking for.
edit here example tried pythons idle:
>>> try: open("epik.sjj") except exception inst: d = inst >>> d filenotfounderror(2, 'no such file or directory') >>> d.args (2, 'no such file or directory') >>> d.args[1] 'no such file or directory' >>>
edit 2: closing program can raise
, error or can use sys.exit()
Comments
Post a Comment