Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to let Try Except output more details? To show where exactly did it happen? - Python [duplicate]

Tags:

python

if we input

10/0

it will output: (Question here --- desired output while using Try Except)

Traceback (most recent call last):
  File "D:\Python_Projects\00_Live\env\lib\site-packages\IPython\core\interactiveshell.py", line 3427, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-2-e574edb36883>", line 1, in <module>
    10/0
ZeroDivisionError: division by zero

but if we use

try:
    10/0
except Exception as e:
    print(e)

it only output:

division by zero

How do we get python to output the whole errors like in the first case while using Try Except?

like image 498
user14384765 Avatar asked Dec 17 '25 21:12

user14384765


1 Answers

If you want to continue raising the error (which will eventually result in exiting the program and printing a stack trace), you can put raise in the body of an except:

try:
    10/0
except Exception as e:
    print(e)
    raise

If you want to print the stack trace but not raise the exception, see the traceback module: https://docs.python.org/3/library/traceback.html

like image 184
Samwise Avatar answered Dec 20 '25 10:12

Samwise



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!