Python Forum

Full Version: Catching Errors
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am learning about try/catch mechanism and do not understand how the following program works:
import random

def test2():
    i = input('i ?\n')
    j = input('j ?\n')
    try:
        i = float(i)
        j = float(j)
        print(i, j, i/j) # we try it
    except ZeroDivisionError: # in case of division by zero
        print('j should not be equal to 0.0\n')
        test(2) #recursion
    except ValueError: # in case where i or j cannot be casted
        print('enter integers or floats\n')
        test2()


test2()

More specifically, how does it know which except statement to call? There isn't a statement such an if/else statement for example that would direct the code to execute the correct one. Something like if there is a division by zero print "j should not be equal to 0.0" else print "enter integers or floats"

Thanks in advance.

Nevermind,

Later in the material it was stated that these are standard exceptions. I apologize for posting the question.
The ValueError and ZeroDivisionError are names associated with specific exceptions.
When an exception is thrown, the except clause looks at the name, and if it matches, executes the except clause.