print line where error happened (python)
- User
print line where error happened (python)
- Assistant
When debugging in Python, you can utilize the traceback module to capture and print the stack trace, which includes the line where the error occurred. Here's how you can do it:
-
Using Exception Handling with Traceback:
You can wrap your code in a try-except block and use the
tracebackmodule to print the line where the exception occurred.import traceback try: # Your code here x = 1 / 0 # Example to trigger an exception except Exception as e: print("An error occurred:") traceback.print_exc()
-