Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When I catch an exception, how do I get the type, file, and line number?

Catching an exception that would print like this:

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

I want to format it into:

ZeroDivisonError, tmp.py, 1 
like image 507
Claudiu Avatar asked Aug 14 '09 16:08

Claudiu


People also ask

How can I get the line number which threw exception?

Simple way, use the Exception. ToString() function, it will return the line after the exception description. You can also check the program debug database as it contains debug info/logs about the whole application.

How do I catch an exception and print message?

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.


2 Answers

import sys, os  try:     raise NotImplementedError("No error") except Exception as e:     exc_type, exc_obj, exc_tb = sys.exc_info()     fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]     print(exc_type, fname, exc_tb.tb_lineno) 
like image 106
Ants Aasma Avatar answered Oct 19 '22 05:10

Ants Aasma


Simplest form that worked for me.

import traceback  try:     print(4/0) except ZeroDivisionError:     print(traceback.format_exc()) 

Output

Traceback (most recent call last):   File "/path/to/file.py", line 51, in <module>     print(4/0) ZeroDivisionError: division by zero  Process finished with exit code 0 
like image 34
nu everest Avatar answered Oct 19 '22 03:10

nu everest