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?
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)
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With