Python中,自定义异常是指用户根据需求创建的异常类。通常自定义异常会继承自Exception类或其子类。

语法结构 syntax

  • 直接抛出异常, 这种方式针对异常一种简单处理,不需要过于复杂地对错误进行处理和提醒。
raise Exception("description")
try:
    a = "a"
    b = 0

    if a+b!=100:
        raise Exception("a+b is not 100")
    c = a / b
except ValueError:
    print("赋值错误!")
except ZeroDivisionError:
    print("除数不能为零!")
except:
    print("其它异常")
  • 继承Exception类,还是上面的例子,对于两个数的异常提醒要求比较详细,可以通过继承类来解决
# 示例
class ValidationError(Exception):

	def __init__(self, message, value):
		self.message = message
		self.value = value
		super().__init__(self.message)

	def __str__(self):
		return f"{self.message}: {self.value}"
class SummaryError(Exception):

	def __init__(self, message, a, b):
		self.message = message
		self.a = a
		self.b = b
		super().__init__(self.message)

	def __str__(self):
		return f"The summary must be 100, but {a}+{b} = {a+b}"

try:
    a = int(input('Input a:'))
    b = int(input('Input b:'))
    if a+b!=100:
        raise SummaryError('a+b must be 100',a, b)
    c = a / b
except TypeError:
    print("You assigned a wrong type.")
except ZeroDivisionError:
    print("Divisor is zero.")
except Exception as e:
    print(e)
else:
    print("c的值为:",c)
finally:
    print("程序结束!")