class Sub(Exception):
def __init__(self, x, y):
self.x = x
self.y = y
try:
a = int(input('请输入被减数'))
b = int(input('请输入减数'))
if a < b:
raise Sub(a, b)
except Sub as error:
print('异常原因:被减数%d不能小于减数%d' % (error.x, error.y))
else:
c = a - b
print('%d减%d的结果为%d' % (a, b, c))
输出结果:
请输入被减数>? 0
请输入减数>? 1
异常原因:被减数0不能小于减数1
请输入被减数>? 4
请输入减数>? 2
4减2的结果为2
方法一:
def division() :
try :
a, b = int(input("输入两个数字以完成除法(a/b):"))
print("{} / {} = {}".format(a, b, c))
except ZeroDivisionError :
print("Error: The divisor can not be zero") # 除数不能为零!
except IOError :
print("Error:Wrong input or output") # 输入或输出错误”
except ValueError :
print("Error:Wrong value,变量应为数值类型!") # 值错误
except NameError :
print("Error: No characters or strings 变量缺少") # 使用了没有定义的对象,没有字符或字符串
except SyntaxError :
print("Error:No symbols or whitespaces") # 语法错误:无符号或空格
except TypeError :
print("Error: The data type is wrong and must be number") # 数据类型错误,必须要求除数和被除数是数字,不能是字符串或者其他
else :
print(a, '/', b, '=', c)
输出结果:
3/0
Traceback (most recent call last):
File "D:\Anaconda\lib\site-packages\IPython\core\interactiveshell.py", line 2963, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-31-f6cc6d14333b>", line 1, in <module>
3/0
ZeroDivisionError: division by zero
8/2
Out[33]: 4.0
hhhhj/7
NameError: name 'hhhhj' is not defined
方法二:
try:
a = int(input("Please input the first number: "))
b = int(input("Please input the second number: "))
c = a / b
print("{} / {} = {}".format(a, b, c))
except IOError:
print("You input a non-number!")
except ValueError:
print("You input a non-number!")
except ZeroDivisionError:
print("You can not divide a number by zero!")
else:
print("Division done!")
输出结果:
请输入a的值:>? 3
请输入b的值:>? 2
a除以b的结果是:1.5
请输入a的值:>? q
输入不是正确的数字,请重新输入:
请输入a的值:>? f
输入不是正确的数字,请重新输入: