自定义异常的两种方式
一、抛出异常
def greet(name, city): if not isinstance(name, str): raise TypeError("Name must be str") if not isinstance(city, str): raise TypeError("Age must be str") print("My name is %s, and I come from" % (name, city))greet(1, 2)
二、自定义异常(一)
调用父类Exception的__init__方法
class ArgumentError(Exception): def __init__(self, *args, **kwargs): _args = ("参数错误",) + args super(ArgumentError, self).__init__(*_args, **kwargs)def division(a, b): if b == 0: raise ArgumentError("0不能做除数") if not isinstance(a, (int, float)) or not isinstance(b, (int, float)): raise ArgumentError("参数必须是数值型") return a / bdivision(1, 0)division(1,'a')
三、自定义异常(二)
使用__str__方法
class ArgumentError2(Exception): def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs def __str__(self): return "%s" % repr(self.args) + repr(self.kwargs)def division(a, b): if b == 0: raise ArgumentError2("0不能做除数") if not isinstance(a, (int, float)) or not isinstance(b, (int, float)): import datetime raise ArgumentError2("参数必须是数值型", time=datetime.datetime.now().strftime('%F %H:%M:%S')) print(a / b)division(1,'test')