Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, is it possible to print exceptions even when they are being ignored?

Tags:

python

I'm aware that it's possible to ignore exceptions in Python using try...except statements. Is it possible to ignore exceptions in Python when they occur, but still print them?

I tried ignoring the exception here, and therefore, the exception was not printed when it was encountered:

try:
    num = 0
    if num == 0:
        raise Exception("Num must not be 0!")
except Exception:
    pass
    '''The exception is ignored, and is not printed.'''

I've written a simple source-to-source compiler that has a lot of exceptions like these, and I'm not sure how I can ignore the exceptions while still printing them. How can I ensure that the exceptions are printed to the console even when they are being ignored?

like image 510
Anderson Green Avatar asked Nov 29 '22 12:11

Anderson Green


2 Answers

You can print an exception like this.

try:
    x = 1 / 0
except Exception as e:
    print e

EDIT:

As user1354557, gcbirzan, and Jonathan Vanasco pointed out, you can use the traceback and logging modules to get more precise error messages. Error messages printed out these ways will be more verbose, which is (usually) a good thing.

import traceback

try:
    x = 1 / 0
except Exception as e:
    print traceback.format_exc()  # I prefer this to traceback.print_exc()


import logging

try:
    x = 1 / 0
except Exception as e:
    logging.exception(e)
like image 53
FastTurtle Avatar answered May 17 '23 12:05

FastTurtle


If you want a printout of the stack trace, you can use the traceback module:

import traceback
try:
    0/0
except:
    traceback.print_exc()

This would print something like:

Traceback (most recent call last):
  File "example.py", line 3, in <module>
    0/0
ZeroDivisionError: integer division or modulo by zero

Is this what you're looking for?

like image 34
user1354557 Avatar answered May 17 '23 10:05

user1354557