Python3之异常处理

写自动化脚本时经常会用到异常处理,下面将python中的异常处理做一整理:

 

 

注意:以下所有事列中的111.txt文件不存在,所以会引起异常

用法一:try...except...else..类型

1.没有异常时运行:

a = 3
try:
    print(a)
except BaseException as msg:   #用msg变量来接受信息,并将其打印。其中BaseException为所有异常的基类,所有异常都继承与它
    print(msg)
else:
    print("没有异常时执行")

运行结果:

3
没有异常时执行

2.有异常时运行:

a = 3
b = 4
try:
    print(a)
    open("111.txt",'r')       #使用open以只读的方式打开不存在的文件111.txt
    print(b)
except BaseException as msg:  #用msg变量来接受信息并将其打印
    print(msg)
else:
    print("没有异常时执行")

运行结果:

3
[Errno 2] No such file or directory: '111.txt'     ##该条错误信息是msg接收到的信息

上面代码中的print(b)并没有被执行,因为再该行代码的上一步出现异常

 

用法二:try...except...finally...类型

1.没有异常时运行:

a = 3
try:
    print(a)
except BaseException as msg:
    print(msg)
finally:
    print("不管有没有异常都会被执行")

运行结果:

3
不管有没有异常都会被执行

2.有异常时运行:

a = 3
try:
    print(a)
    open('111.txt','r')
except BaseException as msg:   
    print(msg)
finally:
    print("不管有没有异常都会被执行")

运行结果:

3
[Errno 2] No such file or directory: '111.txt'
不管有没有异常都会被执行

 

 

用法三:抛出异常(raise)

a = 3
try:
    print(a)
    open('111.txt','r')
except:
    raise Exception('111.txt no exsit')  #raise用于异常抛出

运行结果:

3
Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
FileNotFoundError: [Errno 2] No such file or directory: '111.txt'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 5, in <module>           #抛出异常
Exception: 111.txt no exsit

 

自定义异常

class TimeError(RuntimeError):       #定义一个异常类,该类应该是典型的继承自Exception类,通过直接或间接的方式
    def __init__(self,arg):
        self.arg = arg


try:
    raise TimeError("Network timeout")   #自定义异常提示
except TimeError as e:
    print(e.arg)

运行结果:

Network timeout

 

posted @ 2019-09-25 17:02  法卡萨多  阅读(802)  评论(0编辑  收藏  举报