Extra Topic: Using try and except
Note: extra topics are not in CS Academy, but are required
and can appear on any future
homework, writing session, quiz, or exam.
This version crashes if you enter a non-integer or if you enter 0:
x = int(input('Enter an integer divisor: '))
print(f'10/{x} == {10/x}')
print('Done!') # will this line run?
This version does not crash:
try:
x = int(input('Enter an integer divisor: '))
print(f'10/{x} == {10/x}')
except:
print('Something went wrong. But we did not crash!')
print('Done!') # will this line run?
Here we handle each error type separately:
try:
x = int(input('Enter an integer divisor: '))
print(f'10/{x} == {10/x}')
except ValueError:
print('Error: you entered a non-integer!')
except ZeroDivisionError:
print('You entered 0, and we cannot divide by 0.')
print('Done!') # will this line run?