【Python面向对象】(13)系统异常以及自定义异常
一、系统异常
""" 捕获异常 """ def test_div(num1, num2): """ 除法 :param num1: :param num2: """ return num1/num2 if __name__ == '__main__': # except后面无异常类型,则默认捕获Exception,则是捕获所有的异常 try: rest1 = test_div(5, 0) print(rest1) # 报错:ZeroDivisionError: division by zero except: print("报错啦") # 输出:报错啦,除数不能为0 # 捕获指定异常 try: rest1 = test_div(5, 0) print(rest1) # 报错:ZeroDivisionError: division by zero except ZeroDivisionError: print("报错啦,除数不能为0") # 输出:报错啦,除数不能为0 try: rest2 = test_div(5, 's') print(rest2) # 报错:TypeError: unsupported operand type(s) for /: 'int' and 'str' except TypeError: print("报错啦,请输入数字") # 输出:报错啦,请输入数字 # 捕获多个异常 try: rest1 = test_div(5, 0) print(rest1) # 报错:ZeroDivisionError: division by zero except (ZeroDivisionError, TypeError): print("报错啦,除数不能为0或者请输入数字") # 输出:报错啦,除数不能为0或者请输入数字
二、自定义异常
""" 自定义异常 """ class MyException(Exception): """我的异常类""" error_code = "" error_msg = "" def __init__(self, error_code=None, error_msg=None): self.error_code = self.error_code if self.error_code else error_code self.error_msg = self.error_msg if self.error_msg else error_msg def __str__(self): return "Error: {0} - {1}".format(self.error_code, self.error_msg) class InvalidException(MyException): """当参数不合法时触发""" error_code = "400" error_msg = "两个必须为整数" def divide(num1, num2): """除法""" # 两个数必须为整数 if not isinstance(num1, int) or not isinstance(num2, int): raise InvalidException() # 除数不能为0 if num2 == 0: raise MyException("401", "除数不能为0") return num1/num2 if __name__ == "__main__": try: res = divide(5, "s") print(res) except InvalidException as e: print(e) except MyException as e: print(e)