Python 异常(十五)

首先申明下,本文为笔者学习《Python学习手册》的笔记,并加入笔者自己的理解和归纳总结。

每当Python运行时程序发生错误,Python会引发异常。可以在程序中捕捉和响应异常,或者忽略异常。

1. 默认异常处理

默认异常处理就是打印错误信息

>>> def fun(val1, val2):            # 定义一个加法函数
    return val1 + val2

>>> fun("Hello World!", 13)         # 字符串和数字不能相加
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    fun("Hello World!", 13)
  File "<pyshell#2>", line 2, in fun
    return val1 + val2
TypeError: cannot concatenate 'str' and 'int' objects

2. 捕捉异常

try/except代码块可以捕捉异常,并在except中处理。

>>> def fun(val1, val2):
    try:
        print val1 + val2
    except TypeError:
        print "get except"

>>> fun("hello", 13)
get except

except可以捕捉一个或多个异常

>>> def fun():
    try:
        action()                    # 某个方法
    except TypeError:               # 捕捉异常
        print "get TypeError"
    except IndexError, KeyError:    # 可以同时捕捉多个异常
        print "get IndexError or KeyError"
    except:                         # 捕捉任意异常,类似于except Exception
        print "get exception"

>>> def action():                   # TypeError
    "Hello World" + 5
>>> fun()
get TypeError

>>> def action():                   # IndexError
    "hello"[10]
>>> fun()
get IndexError or KeyError

>>> def action():                   #  ZeroDivisionError
	1/0
>>> fun()
get exception

3. else语句

else语句与except配合使用,如果没有遇到异常发生,执行else语句。
else语句至少要有一个except语句。

>>> def fun(val1, val2):
    try:
        print val1 + val2
    except TypeError:
        print "get except"
    else:
        print "no error occur"

>>> fun(3, 4)                       # 正常运行,调用else语句
7
no error occur

>>> fun("hello", 5)                 # 发生异常,不调用else语句
get except

4. finally语句

不管try代码中是否发生异常,finally语句都会执行。

>>> def fun(val1, val2):
    try:
        return val1 + val2
    finally:
        print "In finally"

>>> fun(3, 4)                       # 正常运行,调用finally语句
In finally
7

>>> fun("Hello", 4)                 # 发生异常,同样调用finally语句
In finally
Traceback (most recent call last):
  File "<pyshell#27>", line 1, in <module>
    fun("Hello", 4)
  File "<pyshell#25>", line 3, in fun
    return val1 + val2
TypeError: cannot concatenate 'str' and 'int' objects

5. 引发异常

raise语句可以抛出一个异常,或者一个异常实例。

>>> raise TypeError
Traceback (most recent call last):
  File "<pyshell#63>", line 1, in <module>
    raise TypeError
TypeError

>>> raise TypeError("TypeError instance")
Traceback (most recent call last):
  File "<pyshell#64>", line 1, in <module>
    raise TypeError("TypeError instance")
TypeError: TypeError instance

raise抛出一个异常时,会自动调用异常类的构造函数来初始化一个异常实例。

assert语句也可以触发异常。

>>> assert False, "You failed"
Traceback (most recent call last):
  File "<pyshell#65>", line 1, in <module>
    assert False, "You failed"
AssertionError: You failed

6. 异常信息

异常是一个实例对象,可以打印异常信息。

>>> try:
    raise TypeError("TypeError instance")
except TypeError as err:
    print err.__class__
    print err.args
    import sys
    print sys.exc_info()[0]
	
<type 'exceptions.TypeError'>
('TypeError instance',)
<type 'exceptions.TypeError'>

7. 自定义异常

自定义异常需要继承Exception

>>> class NoSuchMethodException(Exception):
    pass
>>> raise NoSuchMethodException
Traceback (most recent call last):
  File "<pyshell#69>", line 1, in <module>
    raise NoSuchMethodException
NoSuchMethodException

自定义异常定制打印。

>>> class NoSuchMethodException(Exception):
    def __init__(self, filename, function):
        self.filename = filename
        self.function = function
    def __str__(self):
        return "NoSuchMethod %s at %s" % (self.function, self.filename)

>>> try:
    raise NoSuchMethodException("test.py", "indexAt")
except Exception as excpt:
    print excpt
	
NoSuchMethod indexAt at test.py

相关文章
Python 数字类型(一)
Python 布尔型(二)
Python 字符串(三)
Python 列表(四)
Python 字典(五)
Python 元组(六)
Python 集合(七)
Python 变量和作用域(八)
Python 语句(九)
Python 函数(十)
Python 类(十一)
Python 模块(十二)
Python 文档(十三)
Python 文件(十四)
Python 异常(十五)
Python 运算符重载(十六)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值