Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print an exception in Python?

try:     something here except:     print('the whatever error occurred.') 

How can I print the error/exception in my except: block?

like image 234
TIMEX Avatar asked Sep 27 '09 11:09

TIMEX


People also ask

How do you print an exception in Python?

To catch and print an exception that occurred in a code snippet, wrap it in an indented try block, followed by the command "except Exception as e" that catches the exception and saves its error message in string variable e . You can now print the error message with "print(e)" or use it for further processing.

How do I get exception details in Python?

Catching Exceptions in Python In Python, exceptions can be handled using a try statement. The critical operation which can raise an exception is placed inside the try clause. The code that handles the exceptions is written in the except clause.

How do I print Backtrace in Python?

Print Stack Trace in Python Using traceback Module The traceback. format_exc() method returns a string that contains the information about exception and stack trace entries from the traceback object. We can use the format_exc() method to print the stack trace with the try and except statements.


2 Answers

For Python 2.6 and later and Python 3.x:

except Exception as e: print(e) 

For Python 2.5 and earlier, use:

except Exception,e: print str(e) 
like image 81
jldupont Avatar answered Sep 27 '22 23:09

jldupont


The traceback module provides methods for formatting and printing exceptions and their tracebacks, e.g. this would print exception like the default handler does:

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

Output:

Traceback (most recent call last):   File "C:\scripts\divide_by_zero.py", line 4, in <module>     1/0 ZeroDivisionError: division by zero 
like image 38
Cat Plus Plus Avatar answered Sep 27 '22 22:09

Cat Plus Plus