Python Forum
Catching Errors - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Catching Errors (/thread-18448.html)



Catching Errors - Alienspecimen - May-18-2019

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.


RE: Catching Errors - Larz60+ - May-18-2019

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.