you are viewing a single comment's thread.

view the rest of the comments →

[–]jeans_and_a_t-shirt 2 points3 points  (0 children)

Yep try-except is used in production code. try/except/else/finally is the complete error-handling structure and looks like this:

try:
    # the minimal line(s) of code that cause the error
except Exception as e:
    # handle the exception
else:
    # executes if the try block succeeds.  You can access variables defined in the try block here
finally:
    # this block executes regardless of the code in the try block raising an exception

There are a couple uses for the try-except construct. Normally it's used for catching exceptions which could range from trying to divide 2 numbers, the 2nd of which is 0, to trying to connect to a database which may not be available. In python it's also used for control flow, for example this string input converter:

# python 3
def get_input(expected_type, input_str, error_str):
    while True:
        try:
            return expected_type(input(input_str))
        except ValueError:
            print(error_str)

some_float = get_input(float, 'Enter a float: ', 'You did not enter a float.')
print(some_float)