Python 异常和错误机制,assert 学习总结

一、简介

一般分两种:语法错误异常

总的关键字只有六个:assert, raise,try,except,else,finally

assert(断言)

用于判断一个表达式,在表达式条件为 false 的时候触发异常。
表达式(表达式中也可以携带参数)

assert 可以判断对错的表达式

#等价于
if not expression:
    raise AssertionError

最简单示例:

def assert_test():
    assert True
    print("true 过去了")
    assert  False

if __name__ == '__main__':
    assert_test()

输出:

Traceback (most recent call last):
  File "xxxxxxxxx.py", line 19, in <module>
    assert_test()
  File "xxxxxxxxx.py", line 16, in assert_test
    assert  False
AssertionError
true 过去了

判断当前操作系统的示例

import sys

def assert_test():
    # assert True
    # print("true 过去了")
    # assert  False
    print(sys.platform)
    assert 'linux' in sys.platform

if __name__ == '__main__':
    assert_test()

输出:

win32
Traceback (most recent call last):
  File "XXXXXXXXXXXXXXXX.py", line 22, in <module>
    assert_test()
  File "XXXXXXXXXXXXXXXX.py", line 19, in assert_test
    assert 'linux' in sys.platform
AssertionError

语法错误

通常在控制台显示 SyntaxError 即语法本身的解析就有问题,没有符合书写标准无法解析时出现的错误,但错误的地方一般会使用三角等直接标出或提示

异常

与 Java,C 等 try 机制一致,可以捕获异常,也可以抛出异常,也有finally 操作

二、示例

python 中
(finally 不需要时可以不写)

def exception_test():
    try:
        1/0
    # 多个时写法 except (IOError, TypeError, EOFError, Exception) as e:
    except Exception as e:
        print("error reason:{} ".format(e))
    finally:
        print("finally nothing to do")

if __name__ == '__main__':
    exception_test()

执行结果

error reason:division by zero 
finally nothing to do

流程,同样的先执行 try 内的内容,捕获异常后执行 except 对应的异常内代码。(这里我直接使用了 Exception 可以匹配所有异常,正常来说 还有 IOError, TypeError 之类的)

如果携带了 finally 最后还会执行finally 中的内容

也可以分开 except(即通过匹配不同的错误类型走不同的异常处理代码) 可以如下修改:

def exception_test():
    try:
        1/0
    except IOError as e:
        print("error reason:{} ".format(e))
    except TypeError as e:
        print("ahahaha")
    except EOFError as e:
        print("22222")
    finally:
        print("finally nothing to do")

if __name__ == '__main__':
    exception_test()

由于我这里没有直接匹配到对应错误,所以会出现如下情况:

Traceback (most recent call last):
  File "xxxxxxxxxx.py", line 15, in <module>
    exception_test()
  File "xxxxxxxxxx.py", line 4, in exception_test
    1/0
ZeroDivisionError: division by zero
finally nothing to do

可以看得出 最后控制台是爆出了对应的类型为 ZeroDivisionError ,只要加上对应except 就可以走对应的异常处理代码

同时except 后面的内容是可以被省略的
省略不写将作为默认的处理块,即可以类似如下:

def exception_test():
    try:
        1/0
    except:
        print("啥都没干")
    finally:
        print("finally nothing to do")

if __name__ == '__main__':
    exception_test()

输出结果:

啥都没干
finally nothing to do

try/except…else

即python 额外提供了一种else 写法,只有当 try 中没有发生异常时执行
例如:

def exception_test():
    try:
        1/1
    except:
        print("啥都没干")
    else:
        print("nothing happened")
    finally:
        print("finally nothing to do")

if __name__ == '__main__':
    exception_test()

输出结果

nothing happened
finally nothing to do

raise

异常抛出的机制 类似于 java 的 throw 关键字

def exception_test():
    try:
        1/1
    except:
        print("啥都没干")
    else:
        print("nothing happened")
        raise Exception("我就是要报错")
    finally:
        print("finally nothing to do")

if __name__ == '__main__':
    exception_test()

结果输出:

Traceback (most recent call last):
  File "xxxxxxxxxx.py", line 14, in <module>
    exception_test()
  File "xxxxxxxxxx.py", line 9, in exception_test
    raise Exception("我就是要报错")
Exception: 我就是要报错
nothing happened
finally nothing to do

自定义异常

>>> class MyError(Exception):
        def __init__(self, value):
            self.value = value
        def __str__(self):
            return repr(self.value)
   
>>> try:
        raise MyError(2*2)
    except MyError as e:
        print('My exception occurred, value:', e.value)
   
My exception occurred, value: 4
>>> raise MyError('sss!')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
__main__.MyError: 'sss!'

异常的命名一般都以 Error 结尾,与java 不同,当一个模块可能抛出多个异常时,我们通常会封装一个基础的异常,然后再基于这个基础的异常再分出其子异常

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值