【Python基础】之异常

一、常见异常

try:
    open('abc.txt','r')
except FileNotFoundError:
    print('异常啦!')

输出结果:
======= 异常啦!

我们通过 open()方法以读“r”的方式打开一个 abc.txt 的文件。然后 Python 抛出一个FileNotFoundError 类型的异常,它告诉我们:No such file or directory:“abc.txt”(没有abc.txt 这样的文件或目录)。当然找不到,因为我们根本就没创建这个文件。

既然知道执行 open()一个不存在的文件时会抛 FileNotFoundError 异常,那么我们就可以通过 Python 所提供的 try...except...语句来接收并处理这个异常。

二、基类BaseException

try:
    open(aa)
except BaseException:
    print('异常啦!')


输出结果:
=======
异常啦!

三、msg变量接收异常信息

try:
    open('abc.txt','r')
    print(aa)
except BaseException as msg:
    print(msg)

输出结果:
=======
[Errno 2] No such file or directory: 'abc.txt'

Python中常见的异常如下表:

四、try...except...else的使用

try:
    a = '测试:'
    print(a)
except Exception as msg:
    print(msg)
else:
    print('没有异常!')


输出结果:
=======
测试:
没有异常!

五、try...except...finally的使用

try:
    print(a)
except Exception as msg:
    print(msg)
finally:
    print('我永远被执行!')

输出结果:
======
name 'a' is not defined
我永远被执行!

六、抛出异常raise

from random import randint

#1~9随机数选
number = randint(1,9)

if number % 2 == 0:
    raise NameError('%d is even' %number)
else:
    raise NameError('%d is odd',%number)

输出结果:
======
Traceback (most recent call last):
  File "F:Pytestabnormal.py", line 30, in <module>
    raise NameError("%d is odd" %number)
NameError: 7 is odd
原文地址:https://www.cnblogs.com/Owen-ET/p/7097008.html