Python Forum

Full Version: python exception handling handling .... with traceback
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi Team,

I am using below code getting error message.
But I want error properly line by line. I wan to print that error properly line by line.


import traceback
try:
    print(4/0)
except ZeroDivisionError:
   print(traceback.format_exc())
Error:
D:\Python\venv\Scripts\python.exe D:\Python\m12.py Traceback (most recent call last): File "D:\Python\m12.py", line 4, in <module> print(4/0) ZeroDivisionError: division by zero
Expected output:
Output:
File "D:\Python\m12.py" line 4 print(4/0) ZeroDivisionError: division by zero
Hi Team,

I found little bit of solution , which I was looking for.
I am splitting errors message into list. and printing each value.

is there any alternate easy solution. to get correct info. thanks in advance !
import traceback
try:
    print(4/0)
except ZeroDivisionError:
   error = traceback.format_exc()
   for e in (error.split('\n')):
       if not "Traceback" in e:
           print(e)
Thanks
mg
These look the same to me.
import traceback

def func(x):
    try:
        return x/0
    except ZeroDivisionError as e:
        print("######################")
        traceback.print_tb(e.__traceback__)
        traceback.print_exception(e)
        print("######################")
        error = traceback.format_exc()
        for e in (error.split('\n')):
            if not "Traceback" in e:
                print(e)
        print("######################")
        return None

def intermediary(x):
    return func(x)

print("func(0) =", intermediary(0))
print("Got here!")
I do not like that the traceback is cuts off at the try. It doesn't show that func() was called by intermediary() which in turn was called from main.
You could perhaps use specialized modules that people wrote to prettify the Python traceback such as this one (untested)