python异常处理

try & except 块

写代码的时候,出现错误必不可免,即使代码没有问题,也可能遇到别的问题。

看下面这段代码:

import math

while True:
    text = raw_input('> ')
    if text[0] == 'q':
        break
    x = float(text)
    y = math.log10(x)
    print "log10({0}) = {1}".format(x, y)

这段代码接收命令行的输入,当输入为数字时,计算它的对数并输出,直到输入值为 q 为止。

乍看没什么问题,然而当我们输入0或者负数时:

import math

while True:
    text = raw_input('> ')
    if text[0] == 'q':
        break
    x = float(text)
    y = math.log10(x)
    print "log10({0}) = {1}".format(x, y)
> -1



---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-1-ceb8cf66641b> in <module>()
      6         break
      7     x = float(text)
----> 8     y = math.log10(x)
      9     print "log10({0}) = {1}".format(x, y)


ValueError: math domain error

log10 函数会报错,因为不能接受非正值。

一旦报错,程序就会停止执行,如果不希望程序停止执行,那么我们可以添加一对 try & except

import math

while True:
    try:
        text = raw_input('> ')
        if text[0] == 'q':
            break
        x = float(text)
        y = math.log10(x)
        print "log10({0}) = {1}".format(x, y)
    except ValueError:
        print "the value must be greater than 0"

一旦 try 块中的内容出现了异常,那么 try 块后面的内容会被忽略,Python会寻找 except 里面有没有对应的内容,如果找到,就执行对应的块,没有则抛出这个异常。

在上面的例子中,try 抛出的是 ValueErrorexcept 中有对应的内容,所以这个异常被 except 捕捉到,程序可以继续执行:

import math

while True:
    try:
        text = raw_input('> ')
        if text[0] == 'q':
            break
        x = float(text)
        y = math.log10(x)
        print "log10({0}) = {1}".format(x, y)
    except ValueError:
        print "the value must be greater than 0"
> -1
the value must be greater than 0
> 0
the value must be greater than 0
> 1
log10(1.0) = 0.0
> q

本人对于Python学习创建了一个小小的学习圈子,为各位提供了一个平台,大家一起来讨学习Python。欢迎各位到来Python学习群:960410445一起讨论视频分享学习。Python是未来的展方向,正在挑战我们的分析能力及对世界的认知方式,因此,我们与时俱进,迎接变化,并不断成长,掌握Python核心技术,才是掌握真正的价值所在。

捕捉不同的错误类型

import math

while True:
    try:
        text = raw_input('> ')
        if text[0] == 'q':
            break
        x = float(text)
        y = 1 / math.log10(x)
        print "log10({0}) = {1}".format(x, y)
    except ValueError:
        print "the value must be greater than 0"

假设我们将这里的 y 更改为 1 / math.log10(x),此时输入 1

import math

while True:
    try:
        text = raw_input('> ')
        if text[0] == 'q':
            break
        x = float(text)
        y = 1 / math.log10(x)
        print "log10({0}) = {1}".format(x, y)
    except ValueError:
        print "the value must be greater than 0"
> 1



---------------------------------------------------------------------------

ZeroDivisionError                         Traceback (most recent call last)

<ipython-input-3-7607f1ae6af9> in <module>()
      7             break
      8         x = float(text)
----> 9         y = 1 / math.log10(x)
     10         print "log10({0}) = {1}".format(x, y)
     11     except ValueError:


ZeroDivisionError: float division by zero

因为我们的 except 里面并没有 ZeroDivisionError,所以会抛出这个异常,我们可以通过两种方式解决这个问题:

捕捉所有异常

except 的值改成 Exception 类,来捕获所有的异常。

import math

while True:
    try:
        text = raw_input('> ')
        if text[0] == 'q':
            break
        x = float(text)
        y = 1 / math.log10(x)
        print "1 / log10({0}) = {1}".format(x, y)
    except Exception:
        print "invalid value"
> 1
invalid value
> 0
invalid value
> -1
invalid value
> 2
1 / log10(2.0) = 3.32192809489
> q

指定特定值

这里,我们把 ZeroDivisionError 加入 except

import math

while True:
    try:
        text = raw_input('> ')
        if text[0] == 'q':
            break
        x = float(text)
        y = 1 / math.log10(x)
        print "1 / log10({0}) = {1}".format(x, y)
    except (ValueError, ZeroDivisionError):
        print "invalid value"
> 1
invalid value
> -1
invalid value
> 0
invalid value
> q

或者另加处理:

import math

while True:
    try:
        text = raw_input('> ')
        if text[0] == 'q':
            break
        x = float(text)
        y = 1 / math.log10(x)
        print "1 / log10({0}) = {1}".format(x, y)
    except ValueError:
        print "the value must be greater than 0"
    except ZeroDivisionError:
        print "the value must not be 1"
> 1
the value must not be 1
> -1
the value must be greater than 0
> 0
the value must be greater than 0
> 2
1 / log10(2.0) = 3.32192809489
> q

事实上,我们还可以将这两种方式结合起来,用 Exception 来捕捉其他的错误:

import math

while True:
    try:
        text = raw_input('> ')
        if text[0] == 'q':
            break
        x = float(text)
        y = 1 / math.log10(x)
        print "1 / log10({0}) = {1}".format(x, y)
    except ValueError:
        print "the value must be greater than 0"
    except ZeroDivisionError:
        print "the value must not be 1"
    except Exception:
        print "unexpected error"
> 1
the value must not be 1
> -1
the value must be greater than 0
> 0
the value must be greater than 0
> q

得到异常的具体信息

在上面的例子中,当我们输入不能转换为浮点数的字符串时,它输出的是 the value must be greater than 0,这并没有反映出实际情况。

float('a')
---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-8-99859da4e72c> in <module>()
----> 1 float('a')


ValueError: could not convert string to float: a

为了得到异常的具体信息,我们将这个 ValueError 具现化:

import math

while True:
    try:
        text = raw_input('> ')
        if text[0] == 'q':
            break
        x = float(text)
        y = 1 / math.log10(x)
        print "1 / log10({0}) = {1}".format(x, y)
    except ValueError as exc:
        if exc.message == "math domain error":
            print "the value must be greater than 0"
        else:
            print "could not convert '%s' to float" % text
    except ZeroDivisionError:
        print "the value must not be 1"
    except Exception as exc:
        print "unexpected error:", exc.message
> 1
the value must not be 1
> -1
the value must be greater than 0
> aa
could not convert 'aa' to float
> q

同时,我们也将捕获的其他异常的信息显示出来。

这里,exc.message 显示的内容是异常对应的说明,例如

ValueError: could not convert string to float: a

对应的 message

could not convert string to float: a

当我们使用 except Exception 时,会捕获所有的 Exception 和它派生出来的子类,但不是所有的异常都是从 Exception 类派生出来的,可能会出现一些不能捕获的情况,因此,更加一般的做法是使用这样的形式:

try:
    pass
except:
    pass

这样不指定异常的类型会捕获所有的异常,但是这样的形式并不推荐。

自定义异常

异常是标准库中的类,这意味着我们可以自定义异常类:

class CommandError(ValueError):
    pass

这里我们定义了一个继承自 ValueError 的异常类,异常类一般接收一个字符串作为输入,并把这个字符串当作异常信息,例如:

valid_commands = {'start', 'stop', 'pause'}

while True:
    command = raw_input('> ')
    if command.lower() not in valid_commands:
        raise CommandError('Invalid commmand: %s' % command)
> bad command



---------------------------------------------------------------------------

CommandError                              Traceback (most recent call last)

<ipython-input-11-0e1f81a1136d> in <module>()
      4     command = raw_input('> ')
      5     if command.lower() not in valid_commands:
----> 6         raise CommandError('Invalid commmand: %s' % command)


CommandError: Invalid commmand: bad command

我们使用 raise 关键词来抛出异常。

我们可以使用 try/except 块来捕捉这个异常:

valid_commands = {'start', 'stop', 'pause'}

while True:
    command = raw_input('> ')
    try:
        if command.lower() not in valid_commands:
            raise CommandError('Invalid commmand: %s' % command)
    except CommandError:
        print 'Bad command string: "%s"' % command

由于 CommandError 继承自 ValueError,我们也可以使用 except ValueError 来捕获这个异常。

finally

try/catch 块还有一个可选的关键词 finally。

不管 try 块有没有异常, finally 块的内容总是会被执行,而且会在抛出异常前执行,因此可以用来作为安全保证,比如确保打开的文件被关闭。。

try:
    print 1
finally:
    print 'finally was called.'
1
finally was called.

在抛出异常前执行:

try:
    print 1 / 0
finally:
    print 'finally was called.'
finally was called.



---------------------------------------------------------------------------

ZeroDivisionError                         Traceback (most recent call last)

<ipython-input-13-87ecdf8b9265> in <module>()
      1 try:
----> 2     print 1 / 0
      3 finally:
      4     print 'finally was called.'


ZeroDivisionError: integer division or modulo by zero

如果异常被捕获了,在最后执行:

try:
    print 1 / 0
except ZeroDivisionError:
    print 'divide by 0.'
finally:
    print 'finally was called.'
divide by 0.
finally was called.

警告

出现了一些需要让用户知道的问题,但又不想停止程序,这时候我们可以使用警告:

首先导入警告模块:

import warnings

在需要的地方,我们使用 warnings 中的 warn 函数:

warn(msg, WarningType = UserWarning)
def month_warning(m):
    if not 1<= m <= 12:
        msg = "month (%d) is not between 1 and 12" % m
        warnings.warn(msg, RuntimeWarning)

month_warning(13)
c:\Anaconda\lib\site-packages\IPython\kernel\__main__.py:4: RuntimeWarning: month (13) is not between 1 and 12

有时候我们想要忽略特定类型的警告,可以使用 warningsfilterwarnings 函数:

filterwarnings(action, category)

action 设置为 'ignore' 便可以忽略特定类型的警告:

warnings.filterwarnings(action = 'ignore', category = RuntimeWarning)

month_warning(13)
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,402评论 6 499
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,377评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,483评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,165评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,176评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,146评论 1 297
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,032评论 3 417
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,896评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,311评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,536评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,696评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,413评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,008评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,659评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,815评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,698评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,592评论 2 353

推荐阅读更多精彩内容