python3.5入门笔记(11) 异常

为什么要编写异常代码?

如果不编写异常代码,当代码存在异常时会进行报错,无法继续执行代码;编写异常代码后,捕捉当异常后,可以跟据相应的代码进行错误提示,从而使程序继续执行下去

常见异常

Exception        常规错误的基类

AttributeError     对象没有这个属性

IOError           输入/输出操作失败

IndexError        序列中没有此索引(index)

KeyError          映射中没有这个键

NameError        未声明/初始化对象 (没有属性)

SyntaxError        Python 语法错误

SystemError       一般的解释器系统错误

ValueError        传入无效的参数

SystemExit      解释器请求退出

BaseException   所有异常的基类

AssertionError    断言语句失败

ZeroDivisionError (或取模) (所有数据类型)

TypeError         对类型无效的操作

 

例1(try捕捉异常)

def exp_exception(x,y):

    try:

        a=x/y

        print('a=',a)

        return a

    except Exception:

        print('程序异常,被除数不能为0')

exp_exception(2,0)

>>>程序异常,被除数不能为0

例2:

#-*-coding:utf-8-*-

def mult_exceotion(x,y):

    try:

        a=x/y

        b=name

    except ZeroDivisionError:

        print('this is ZeroDivisionError')

mult_exceotion(2,0)

>>> this is ZeroDivisionError

mult_exceotion(2,1)

>>> NameError: name 'name' is not defined

例3(多异常):

#-*-coding:utf-8-*-

def mult_exceotion(x,y):

    try:

        a=x/y

        b=name

    except (ZeroDivisionError,NameError,TypeError):

        print('one of ZeroDivisionError or NameError or TypeError')

mult_exceotion(2,1)

>>> one of ZeroDivisionError or NameError or TypeError

例4(捕捉异常信息):

#-*-coding:utf-8-*-

def mult_exceotion(x,y):

    try:

        a=x/y

        b=name

    except (ZeroDivisionError,NameError,TypeError) as e:

        print(e)

mult_exceotion(2,1)

>>> name 'name' is not defined

例5(无法判断是何种异常):

#-*-coding:utf-8-*-

def mult_exceotion(x,y):

    try:

        a=x/y

        b=name

    except :

        print('Error happened')

mult_exceotion(2,'')

>>>Error happened

一般不建议用此方法,因为无法对异常进行判断,从而解决异常错误

例6(和else一起使用)

#-*-coding:utf-8-*-

def mult_exceotion(x,y):

    try:

        a=x/y

    except (ZeroDivisionError,NameError,TypeError) as e:

        print(e)

    else:

        print('it went as exception')

mult_exceotion(2,1)

>>> it went as exception

例7(自定义异常):

#-*-coding:utf-8-*-

class MyError(Exception):

    def __init__(self):

        pass

    def __str__(self):

        return 'this is self define error'

def my_error_test():

    try:

        raise MyError()  #raise用来抛出异常

    except MyError as e:

        print('exception info:',e)

my_error_test()

>>> exception info: this is self define error

例8(finally):

#-*-coding:utf-8-*-

def mult_exceotion(x,y):

    try:

        a=x/y

    except ZeroDivisionError as e:

        print(e)

    finally:

        print('no matter what happened')

mult_exceotion(2,0)

>>>division by zero

>>>no matter what happened

发布了28 篇原创文章 · 获赞 1 · 访问量 3185

猜你喜欢

转载自blog.csdn.net/pdd51testing/article/details/83865482