이렇게하면 유형을 foo()변경해도에 변경하지 않아도됩니다 bar().
def foo():
try:
raise IOError('Stuff')
except:
raise
def bar(arg1):
try:
foo()
except Exception as e:
raise type(e)(e.message + ' happens at %s' % arg1)
bar('arg1')
Traceback (most recent call last):
File "test.py", line 13, in <module>
bar('arg1')
File "test.py", line 11, in bar
raise type(e)(e.message + ' happens at %s' % arg1)
IOError: Stuff happens at arg1
업데이트 1
원래 역 추적을 유지하는 약간의 수정이 있습니다.
...
def bar(arg1):
try:
foo()
except Exception as e:
import sys
raise type(e), type(e)(e.message +
' happens at %s' % arg1), sys.exc_info()[2]
bar('arg1')
Traceback (most recent call last):
File "test.py", line 16, in <module>
bar('arg1')
File "test.py", line 11, in bar
foo()
File "test.py", line 5, in foo
raise IOError('Stuff')
IOError: Stuff happens at arg1
업데이트 2
Python 3.x의 경우 첫 번째 업데이트의 코드가 구문 상 올바르지 않으며 2012-05-16의 PEP 352로 변경되어message 속성 이 있다는 아이디어 BaseException가 취소되었습니다 (첫 번째 업데이트는 2012-03-12에 게시 됨) . 따라서 현재 Python 3.5.2에서는 트레이스 백을 유지하고 function의 예외 유형을 하드 코딩하지 않기 위해 이러한 행을 따라 무언가를 수행해야합니다 bar(). 또한 다음 줄이 있습니다.
During handling of the above exception, another exception occurred:
표시된 추적 메시지에
# for Python 3.x
...
def bar(arg1):
try:
foo()
except Exception as e:
import sys
raise type(e)(str(e) +
' happens at %s' % arg1).with_traceback(sys.exc_info()[2])
bar('arg1')
업데이트 3
답 인해 구문의 차이에 "아니오"로 보일 수도 있지만 파이썬 2와 3 모두에서 작동 할 수있는 방법이 있었다 경우 주석이 물었다가 있다 같은 도우미 함수를 사용하여 그 주위에 방법 reraise()의 six애드온은 모듈에. 따라서 어떤 이유로 라이브러리를 사용하지 않으려면 아래는 단순화 된 독립형 버전입니다.
또한 reraise()함수 내에서 예외가 다시 발생하기 때문에 발생 하는 모든 추적에 표시되지만 최종 결과는 원하는 것입니다.
import sys
if sys.version_info.major < 3: # Python 2?
# Using exec avoids a SyntaxError in Python 3.
exec("""def reraise(exc_type, exc_value, exc_traceback=None):
raise exc_type, exc_value, exc_traceback""")
else:
def reraise(exc_type, exc_value, exc_traceback=None):
if exc_value is None:
exc_value = exc_type()
if exc_value.__traceback__ is not exc_traceback:
raise exc_value.with_traceback(exc_traceback)
raise exc_value
def foo():
try:
raise IOError('Stuff')
except:
raise
def bar(arg1):
try:
foo()
except Exception as e:
reraise(type(e), type(e)(str(e) +
' happens at %s' % arg1), sys.exc_info()[2])
bar('arg1')
message속성에 대한 문서를 찾는 동안 이 SO 질문 인 BaseException.message는 Python 2.6에서 더 이상 사용되지 않으므로 사용이 권장되지 않는 것으로 보입니다 (그리고 왜 문서에 없는지).