program story

Python에서 예외를 인쇄하는 방법은 무엇입니까?

inputbox 2020. 10. 3. 10:37
반응형

Python에서 예외를 인쇄하는 방법은 무엇입니까?


try:
    something here
except:
    print('the whatever error occurred.')

except:블록 에서 오류 / 예외를 어떻게 인쇄 할 수 있습니까?


Python 2.6 이상 및 Python 3.x의 경우 :

except Exception as e: print(e)

Python 2.5 이하의 경우 다음을 사용합니다.

except Exception,e: print str(e)

traceback모듈에 대한 방법을 제공합니다 서식 및 예외 인쇄 및 자신의 역 추적을 기본 핸들러가하는 것처럼 예외를 인쇄 할이 예 :

import traceback

try:
    1/0
except Exception:
    traceback.print_exc()

산출:

Traceback (most recent call last):
  File "C:\scripts\divide_by_zero.py", line 4, in <module>
    1/0
ZeroDivisionError: division by zero

Python 2.6 이상 에서는 약간 더 깔끔합니다.

except Exception as e: print(e)

이전 버전에서는 여전히 읽기 쉽습니다.

except Exception, e: print e

오류 문자열을 전달하려는 경우 다음은 오류 및 예외 (Python 2.6)의 예입니다.

>>> try:
...    raise Exception('spam', 'eggs')
... except Exception as inst:
...    print type(inst)     # the exception instance
...    print inst.args      # arguments stored in .args
...    print inst           # __str__ allows args to printed directly
...    x, y = inst          # __getitem__ allows args to be unpacked directly
...    print 'x =', x
...    print 'y =', y
...
<type 'exceptions.Exception'>
('spam', 'eggs')
('spam', 'eggs')
x = spam
y = eggs

(@jldupont의 답변에 대한 댓글로 남기려고했지만 평판이 충분하지 않습니다.)

I've seen answers like @jldupont's answer in other places as well. FWIW, I think it's important to note that this:

except Exception as e:
    print(e)

will print the error output to sys.stdout by default. A more appropriate approach to error handling in general would be:

except Exception as e:
    print(e, file=sys.stderr)

(Note that you have to import sys for this to work.) This way, the error is printed to STDERR instead of STDOUT, which allows for the proper output parsing/redirection/etc. I understand that the question was strictly about 'printing an error', but it seems important to point out the best practice here rather than leave out this detail that could lead to non-standard code for anyone who doesn't eventually learn better.

I haven't used the traceback module as in Cat Plus Plus's answer, and maybe that's the best way, but I thought I'd throw this out there.


One liner error raising can be done with assert statements if that's what you want to do. This will help you write statically fixable code and check errors early.

assert type(A) is type(""), "requires a string"

If you want to print the message to stderr then exit with a status code of 1 (error):

import sys

try:
    ...
except Exception as e:
    sys.exit("Message to print to stderr")

참고URL : https://stackoverflow.com/questions/1483429/how-to-print-an-exception-in-python

반응형