5

(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?

Community
  • 1
  • 1
  • 3
    Just put the `try`/`except` inside the `if` instead of inside the function. The point of exceptions is that they propagate back to callers, so that they can be handled by the layer that knows what to do with them.. – Mark Reed Aug 18 '15 at 09:05
  • Given that you specify in the docstring that the argument must be a string that can be converted to a `float` *why not just use `float()`? Then, as @MarkReed says, catch the error where you're *calling* the function. – jonrsharpe Aug 18 '15 at 09:20

1 Answers1

5

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()
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
geckon
  • 8,316
  • 4
  • 35
  • 59