0
import sys
import linecache

# copied from somewhere
def PrintException():
    exc_type, exc_obj, tb = sys.exc_info()
    f = tb.tb_frame
    lineno = tb.tb_lineno
    filename = f.f_code.co_filename
    linecache.checkcache(filename)
    line = linecache.getline(filename, lineno, f.f_globals)
    print 'EXCEPTION IN ({}, LINE {} "{}"): {}'.format(filename, lineno, line.strip(), exc_obj)

def m1():
    # some code

try:
    try:
        m1()
    except:
        PrintException()
except:
    PrintException()

It writes the Exception line's number of m1()-called line, but I need to know the Exception line's number exactly in function m1. Could you please say how to know it?

5
  • 4
    what is the purpose of nested try-except? Commented Oct 20, 2017 at 5:53
  • 1
    do you mean - it gives you the no of line from where m1() is called and you want the no of line where exactly the exception is (in this case in m1() method definition?). Commented Oct 20, 2017 at 5:57
  • @Azat Ibrakov In so I tried to print line's number Exception nested in m1 Commented Oct 20, 2017 at 5:59
  • @Ankush Rathi Yes Commented Oct 20, 2017 at 6:01
  • @AzatIbrakov If you fail once, try, try again. Commented Oct 20, 2017 at 6:03

1 Answer 1

1

To get the exception you have to loop through .tb_next

import requests, re, time, json, urllib2
import math, os, time
from datetime import datetime

import sys
import linecache

# copied from somewhere
def PrintException():
    exc_type, exc_obj, tb = sys.exc_info()
    f = tb.tb_frame
    lineno = tb.tb_lineno
    if tb.tb_next:
        tb_next = tb.tb_next
        while tb_next: # loop until the value is 'None'
          lineno = tb_next.tb_lineno
          tb_next = tb_next.tb_next
    filename = f.f_code.co_filename
    linecache.checkcache(filename)
    line = linecache.getline(filename, lineno, f.f_globals)
    print 'EXCEPTION IN ({}, LINE {} "{}"): {}'.format(filename, lineno, line.strip(), exc_obj)

def m1():
    # some code
    raise ValueError('Value error')

try:
    try:
        m1()
    except:
        PrintException()
except:
    PrintException()

it will output line 25 not 29 or line not with m1()

EXCEPTION IN (main.py, LINE 25 "raise ValueError('Value error')"): Value error
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.