Some excercise about exception issue in Python3.5
Sample Zero:
#!/usr/bin/env python3
try: # hello exception !
x = input("Enter the first number: ")
y = input("Enter the second number: ")
print(type(x))
print(type(y))
print("res = ", int(x)/int(y)) # x, y is string
except ZeroDivisionError:
print("The second number can't be zero !")
Sample One:
#!/usr/bin/env python3
class MuffledCalculator:
muffled = False
def calc(self, expr):
try: # catch exception
return eval(expr)
except ZeroDivisionError:
if self.muffled:
print("Division by zero is illegal !")
else:
raise
calculator = MuffledCalculator()
print(calculator.calc('10/2'))
#calculator.muffled = True
print(calculator.calc('10/0'))
Sample Two:
#!/usr/bin/env python3
try: #more than one except branch
x = input("Enter the first number: ")
y = input("Enter the second number: ")
print(type(x))
print(type(y))
print(x/y)
except ZeroDivisionError:
print("The second number can't be zero !")
except TypeError:
print("The inputs are not all digital number, are they ?")
Sample Three:
#!/usr/bin/env python3
try: # catch more exception cases once
x = input("Enter the first number: ")
y = input("Enter the second number: ")
print(type(x))
print(type(y))
print("res = ", x/y)
except (TypeError, ZeroDivisionError, NameError):
print("Your inputs are bogus !")
Sample Four:
#!/usr/bin/env python3
try: # display exception type
x = input("Enter the first number: ")
y = input("Enter the second number: ")
print(type(x))
print(type(y))
print("res = ", x/y)
#print("res = ", int(x)/int(y))
except (TypeError, ZeroDivisionError) as e:
print("get exception:", e)
Sample Five:
#!/usr/bin/env python3
while True: # ignore exception if it does not matter
try:
x = input("Enter the first number: ")
y = input("Enter the second number: ")
print(type(x))
print(type(y))
print("res = ", int(x)/int(y))
except Exception as e:
print("Invalid inputs:", e)
print("Please enter numbers ...")
else:
break