Anderson Green
Anderson Green

Reputation: 31840

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

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?

Upvotes: 4

Views: 4952

Answers (5)

FastTurtle
FastTurtle

Reputation: 2311

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)

Upvotes: 10

kindall
kindall

Reputation: 184260

It's possible to do this globally, even in code you didn't write (such as a library module) using a trace function.

import sys

def print_exceptions(frame, event, arg):
    if event == "exception":
        sys.excepthook(*arg)
    return print_exceptions

sys.settrace(print_exceptions)

Note that the trace function is called for every statement executed while it is in effect and may therefore significantly slow down your script's execution. Another minor issue is that any unhandled exception will be printed twice (once by this hook, again by Python itself when exiting the script).

If you want to customize the output, you can dig the information you want out of arg (it's a 3-tuple of the exception type, the error message, and a traceback object) and frame (which includes a reference to the current code object, from which its name can be obtained, as well as the source filename and line number).

Upvotes: 0

user1354557
user1354557

Reputation: 2503

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?

Upvotes: 6

Ayush
Ayush

Reputation: 42450

By ignore, I suppose you mean you want to print it, but not catch it, and allow it to bubble up the call stack. You can do that by catching the exception, printing it, and then re-throwing it.

try :
  # do something
except Exception as e:
  print e
  raise e

Upvotes: 1

gcbirzan
gcbirzan

Reputation: 1514

You should take a look at the logging module. It has support for logging exceptions with traceback (either via logger.exception or by passing exc_info as a keyword parameter to any logging function).

Upvotes: 4

Related Questions