Python에서 exception이 생긴 라인 숫자값을 어떻게 구할 수 있나요?

3주 전 질문 3주 전 토론 10 views

아래 코드를 실행하면

try:
    print("a" + 1)
except Exception as error_message:
    print("There was an error: " + str(error_message)) 

 

이런 에러가 뜹니다.

There was an error: can only concatenate str (not "int") to str

 

여기서 이 코드 부분을

print("There was an error: " + str(error_message))

 

아래처럼 라인 숫자를 출력하고 싶은데요.

try:
    print("a" + 1)
except Exception as error_message and linenumber as linenumber:
    print("There was an error: " + str(error_message) + ". The line where the code failed was " + str(linenumber)

 

이렇게 했을 때 아래처럼 결과가 나오는 걸루요.

There was an error: can only concatenate str (not "int") to str. The line where the code failed was 2 

 

혹시 어떻게 하면 될까요? 

python

2022-06-02 10:25

1개의 해답

이렇게 하시면 됩니다.

import traceback

try:
    print("a" + 1)
except Exception as e:
    print("There was an error: " + e.args[0] + ". The line where the code failed was " + str(traceback.extract_stack()[-1][1]))


2022-06-02 10:27

해결방법이나 팁을 알고 계신다면


© 2022 pinfo. All rights reserved.