一、使用raise抛出异常

python可以自动触发异常,raise(内置函数)的定义为显示的抛出异常,用户可以使用raise进行判断,显式的引发异常,raise执行后程序将不再向下执行。

式例:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = '40kuai'
books_dict = {'name':'python','pages':390}
key = input('查看属性:')
if key in books_dict:
    print(books_dict[key])
else:
    raise KeyError

# 当要查询的属性不在字典中时会触发异常 

raise也可以用户创建自定义的异常

#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = '40kuai'


class helei(Exception):  # 继承 Exception
    def __init__(self, msg):
        self.message = msg

    def __str__(self):  # 被print调用时执行,可以不写
        return self.message

if __name__ == '__main__':
    try:
        raise helei('我的异常')  # 触发异常
    except helei as e:
        print(e)

二、assert使用

assert语句用于检测某个条件表达式是否为真。assert语句又称为断言语句,即assert认为检测的表达式永远为真。

断言用来指定某一操作必须为真。也可以在脚本执行时加上python -O 参数来跳过assert检测。

可以使用assert False 来显示代码编写未完成

 

相关文章:

  • 2021-04-02
  • 2022-12-23
  • 2021-08-21
  • 2022-12-23
  • 2022-01-12
  • 2021-08-22
  • 2021-08-12
  • 2021-11-22
猜你喜欢
  • 2021-07-03
  • 2021-09-13
  • 2021-07-12
  • 2022-01-26
  • 2022-12-23
  • 2022-02-11
  • 2022-12-23
相关资源
相似解决方案