python3 异常处理

异常是由程序的错误引起的,语法上的错误跟异常处理无关,必须在程序运行前就修正

一、基本语法

try:
    int('asdfadsf')    # 被检测的代码块
except ValueError:
    print('=====')    # try中一旦检测到异常,就执行这个位置的逻辑

二、异常类只能用来处理指定的异常情况,如果非指定异常则无法处理

# 未捕获到异常,程序直接报错
 
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)

四、万能异常 在python的异常中,有一个万能异常:Exception,他可以捕获任意异常

s1 = 'hello'
try:
    int(s1)
except Exception as e:
    print(e)
s1 = 'hello'
try:
    int(s1)
except Exception,e:
    '丢弃或者执行其他逻辑'
    print(e)

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

just do it

如果你想要的效果是,对于不同的异常我们需要定制不同的处理逻辑,那就需要用到多分支了。

也可以在多分支后来一个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)

五、异常的其他结构

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('无论异常与否,都会执行该模块,通常是进行清理工作')

六、主动触发异常

#_*_coding:utf-8_*_
__author__ = 'Linhaifeng'

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

七、自定义异常

#_*_coding:utf-8_*_
__author__ = 'Linhaifeng'

class EgonException(BaseException):
    def __init__(self,msg):
        self.msg=msg
    def __str__(self):
        return self.msg

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

八、断言

# assert 条件

assert 1 == 1

assert 1 == 2

原文地址:https://www.cnblogs.com/lucaq/p/7146545.html