2

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?

2 Answers2

2

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

Samwise
  • 68,105
  • 3
  • 30
  • 44
  • How to get it in to a log? I am running the program in a cloud computer – user14384765 Mar 23 '21 at 15:20
  • One option is to have the caller of the program capture its stderr. If you want the program itself to capture the stack trace, have a top-level exception handler that uses that `traceback` module to extract the stack info from uncaught exceptions and then print it to your log file. – Samwise Mar 23 '21 at 15:21
  • 1
    oh you mean like try: 10/0 except Exception as e: logger.exception(e) – user14384765 Mar 23 '21 at 15:31
  • Yes, but rather than putting it around the `10/0`, you might consider putting it around your top-level `main` function -- that way you don't need to put it in every individual place that might raise an exception. This is the huge power of exceptions -- because they keep on raising to the caller until caught, you can implement exception logging across your entire program with a single `try/except` statement! – Samwise Mar 24 '21 at 15:45
1

Instead of using the basic print() function, the more flexible logging module can be used to log the exception. The logging module offers a lot extra functionality, e.g. logging messages into a given log file, logging messages with timestamps and additional information about where the logging happened.

try this :

import logging

try:
    1/0
except Exception as e:
    logging.exception(e)

see documentation

Belhadjer Samir
  • 1,461
  • 7
  • 15