Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Catching Errors
#1
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.
Reply
#2
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Catching a crash within a library code ebolisa 9 3,137 Nov-22-2021, 11:02 AM
Last Post: bowlofred
  Pexpect not catching embeded ssh response luchoArg32 0 2,307 Feb-08-2019, 08:45 AM
Last Post: luchoArg32
  catching / handle index out of range 3Pinter 3 2,673 Feb-04-2019, 01:19 PM
Last Post: buran
  Catching exceptions in embedded code no longer works on 3.7.2? FFMG 5 3,375 Feb-02-2019, 10:15 AM
Last Post: Larz60+
  win32com Events not catching dageci 0 3,744 Aug-06-2018, 03:18 PM
Last Post: dageci

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020