python异常处理

异常

什么是异常?

代码发生异常之后,程序就会中断.

异常处理作用

当代码出现异常时,通过某种方式不让程序中断,合理的跳过去.

为什么要有异常处理

1.用户体验良好
2.使代码更有健壮性、容错性

异常处理的两种方式

1.使用if判断式 只能处理简单的异常,
2.python:为每一种异常定制了一个类型,然后提供了一种特定的语法结构用来进行异常处理

基本语法

try:
     被检测的代码块
except 异常类型:
     try中一旦检测到异常,就执行这个位置的逻辑

读文件的异常处理

try:
    f = open('a.txt')
    g = (line.strip() for line in f)
    print(next(g))
    print(next(g))
    print(next(g))
    print(next(g))
    print(next(g))
except StopIteration:
    f.close()

异常类只能用来处理指定的异常情况.

# 未捕获到异常,程序直接报错
 
s1 = 'hello'
try:
    int(s1)
except IndexError as e:
    print e

多分支

s1 = 'hello'
try:
    int(s1)
except IndexError as e:
    print(e)
except KeyError as e:
    print(e)
except ValueError as e:
    print(e)

万能异常:Exception.

统一用Exception,是可以捕捉所有异常,但意味着你在处理所有异常时都使用同一个逻辑去处理(这里说的逻辑即当前expect下面跟的代码块

s1 = 'hello'
try:
    int(s1)
except Exception as e:
    print(e)

万能异常:Exception.多分支

s1 = 'hello'
try:
    int(s1)
except IndexError as e:
    print(e)
except KeyError as e:
    print(e)
except ValueError as e:
    print(e)

多分支+Exception

s1 = 'hello'
try:
    int(s1)
except IndexError as e:
    print(e)
except KeyError as e:
    print(e)
except ValueError as e:
    print(e)
except Exception as e:
    print(e)

异常的其他机构

结构五:
try else finally
else:如果没有出现异常,则执行else
except:必须依赖try, else:必须依赖except和try
finally:只是依赖于try
finally 在异常出现之前,执行finally语句
应用:
1.用在关闭数据库连接,文件句柄关闭,数据保存,用到finally可以在finally后边用with open 将文件写进去
2.在return结束函数,执行finally代码

s1 = 'hello'
try:
    int(s1)
except IndexError as e:
    print(e)
except KeyError as e:
    print(e)
except ValueError as e:
    print(e)
#except Exception as e:
#    print(e)
else:
    print('try内代码块没有异常则执行我')
finally:
    print('无论异常与否,都会执行该模块,通常是进行清理工作')

主动触发异常

raise ValueError (出现了value错误)

try:
    raise TypeError('类型错误')
except Exception as e:
    print(e)

自定义异常

Python中给你提供的错误类型有很多,但是不是全部的错误
Python会报所有错误信息,但是没有错误的类型
input() 可以使用异常捕获,别的地方慎用

class EvaException(BaseException):
    def __init__(self,msg):
        self.msg=msg
    def __str__(self):
        return self.msg
try:
    raise EvaException('类型错误')
except EvaException as e:
    print(e)

断言

assert 条件
    断言,展示出一种强硬的态度
    assert 条件,assert a == b
    条件不成立直接报错 AssertionError
原文地址:https://www.cnblogs.com/SkyRabbit/p/11342442.html