01Python基础_09异常

栏目: Python · 发布时间: 8年前

内容简介:01Python基础_09异常

1. try & except

原程序:


1 import math
2 
3 while True:
4     text = raw_input('> ')
5     if text[0] == 'q':
6         break
7     x = float(text)
8     y = math.log10(x)
9     print "log10({0}) = {1}".format(x, y)

View Code

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

但是当输入0或者负数时,会报错。

修改后的程序:


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"

View Code

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

运行结果:


> -1
the value must be greater than 0
> 0
the value must be greater than 0
> 1
log10(1.0) = 0.0
> q

View Code

捕捉所有类型错误:

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"

View Code

运行结果:


> 1
invalid value
> 0
invalid value
> -1
invalid value
> 2
1 / log10(2.0) = 3.32192809489
> q

View Code

进一步完善后的程序:


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"

View Code

运行结果:


> 1
the value must not be 1
> -1
the value must be greater than 0
> 0
the value must be greater than 0
> q

View Code

2. finally

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

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

out: 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.'

out: divide by 0.
     finally was called.

View Code

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

计算机和难解性

计算机和难解性

M.R 加里、D.S. 约翰逊 / 张立昂、沈泓 / 科学出版社 / 1987年 / 4.50

本书系统地介绍了NP完全性理论的概念和方法,全书共分为7章和两个附录。第一章粗略地介绍了计算复杂性的一些基本概念和NP完全性理论的意义。第二章至第五章介绍了NP完全性的基本理论和证明的方法。第六章集中研究NP难问题的近似算法。第七章概述了大量计算复杂性中的有关理论课题。 附录A收集了范围广泛、内容丰富的NP完全性和NP难的问题、附录B补充了NP问题的一些最新的进展,既有理论方面的,又有关于具体问题......一起来看看 《计算机和难解性》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

在线进制转换器
在线进制转换器

各进制数互转换器

SHA 加密
SHA 加密

SHA 加密工具