Search code examples
pythonfunctiontry-except

How to trace back the cause of an exception raised within a function?


(This is a follow-up question to the post Python try/except: Showing the cause of the error after displaying my variables.)

I have the following script.py:

import traceback


def process_string(s):
    """
    INPUT
    -----
    s:  string

        Must be convertable to a float

    OUTPUT
    ------
    x:  float
    """

    # validate that s is convertable to a float
    try:
        x = float(s)
        return x
    except ValueError:        
        print
        traceback.print_exc()


if __name__ == '__main__':

    a = process_string('0.25')
    b = process_string('t01')
    c = process_string('201')

Upon execution of script.py, the following message is printed in the terminal window:

Traceback (most recent call last):
  File "/home/user/Desktop/script.py", line 20, in process_string
    x = float(s)
ValueError: could not convert string to float: t01

May I ask if there is a way for traceback.print_exc() to also print in the terminal window which instruction inside the if-main threw the exception which was caught by the try-except clause?


Solution

  • What about this?

    import traceback
    
    
    def process_string(s):
        """
        INPUT
        -----
        s:  string
    
            Must be convertible to a float
    
        OUTPUT
        ------
        x:  float
        """
        return float(s)
    
    
    
    if __name__ == '__main__':
        try:
            a = process_string('0.25')
            b = process_string('t01')
            c = process_string('201')
        except ValueError:        
            print
            traceback.print_exc()