python基础教程(九)

python异常

python用异常对象(exception object)来表示异常情况。遇到错误后,会引发异常。如果异常对象并未被处理或捕捉,程序就会用所谓的 回溯(Traceback, 一种错误信息)终止执行:

>>> 1/0

Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    1/0
ZeroDivisionError: integer division or modulo by zero

raise 语句

为了引发异常,可以使用一个类(Exception的子类)或者实例参数数调用raise 语句。下面的例子使用内建的Exception异常类:

>>> raise Exception    #引发一个没有任何错误信息的普通异常

Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    raise Exception
Exception
>>> raise Exception(‘hyperdrive overload‘)   # 添加了一些异常错误信息

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    raise Exception(‘hyperdrive overload‘)
Exception: hyperdrive overload

系统自带的内建异常类:

>>> import exceptions
>>> dir(exceptions)
[‘ArithmeticError‘, ‘AssertionError‘, ‘AttributeError‘, ‘BaseException‘, ‘BufferError‘, ‘BytesWarning‘, ‘DeprecationWarning‘, ‘EOFError‘, ‘EnvironmentError‘, ‘Exception‘, ‘FloatingPointError‘, ‘FutureWarning‘, ‘GeneratorExit‘, ‘IOError‘, ‘ImportError‘, ‘ImportWarning‘, ‘IndentationError‘, ‘IndexError‘, ‘KeyError‘, ‘KeyboardInterrupt‘, ‘LookupError‘, ‘MemoryError‘, ‘NameError‘, ‘NotImplementedError‘, ‘OSError‘, ‘OverflowError‘, ‘PendingDeprecationWarning‘, ‘ReferenceError‘, ‘RuntimeError‘, ‘RuntimeWarning‘, ‘StandardError‘, ‘StopIteration‘, ‘SyntaxError‘, ‘SyntaxWarning‘, ‘SystemError‘, ‘SystemExit‘, ‘TabError‘, ‘TypeError‘, ‘UnboundLocalError‘, ‘UnicodeDecodeError‘, ‘UnicodeEncodeError‘, ‘UnicodeError‘, ‘UnicodeTranslateError‘, ‘UnicodeWarning‘, ‘UserWarning‘, ‘ValueError‘, ‘Warning‘, ‘WindowsError‘, ‘ZeroDivisionError‘, ‘__doc__‘, ‘__name__‘, ‘__package__‘]

哇!好多,常用的内建异常类:

自定义异常

尽管内建的异常类已经包括了大部分的情况,而且对于很多要求都已经足够了,但有些时候还是需要创建自己的异常类。

和常见其它类一样----只是要确保从Exception类继承,不管直接继承还是间接继承。像下面这样:

>>> class someCustomExcetion(Exception):pass

当然,也可以为这个类添加一些方法。

捕捉异常

我们可以使用 try/except 来实现异常的捕捉处理。

假设创建了一个让用户输入两个数,然后进行相除的程序:

x = input(‘Enter the first number: ‘)
y = input(‘Enter the second number: ‘)
print x/y

#运行并且输入
Enter the first number: 10
Enter the second number: 0

Traceback (most recent call last):
  File "I:/Python27/yichang", line 3, in <module>
    print x/y
ZeroDivisionError: integer division or modulo by zero

为了捕捉异常并做出一些错误处理,可以这样写:

try:
    x = input(‘Enter the first number: ‘)
    y = input(‘Enter the second number: ‘)
    print x/y
except ZeroDivisionError:
  print "输入的数字不能为0!"
  
#再来云行
>>>
Enter the first number: 10
Enter the second number: 0
输入的数字不能为0!           #怎么样?这次已经友好的多了

假如,我们在调试的时候引发异常会好些,如果在与用户的进行交互的过程中又是不希望用户看到异常信息的。那如何开启/关闭 “屏蔽”机制?

class MuffledCalulator:
    muffled = False   #这里默认关闭屏蔽
    def calc(self,expr):
        try:
            return eval(expr)
        except ZeroDivisionError:
            if self.muffled:
                print ‘Divsion by zero is illagal‘
            else:
                raise

#运行程序:
>>> calculator = MuffledCalulator()
>>> calculator.calc(‘10/2‘)
5
>>> calculator.clac(‘10/0‘)

Traceback (most recent call last):
  File "<pyshell#30>", line 1, in <module>
    calculator.clac(‘10/0‘)
AttributeError: MuffledCalulator instance has no attribute ‘clac‘   #异常信息被输出了

>>> calculator.muffled = True   #现在打开屏蔽
>>> calculator.calc(‘10/0‘)
Divsion by zero is illagal 

多个except 子句

如果运行上面的(输入两个数,求除法)程序,输入面的内容,就会产生另外一个异常:

try:
    x = input(‘Enter the first number: ‘)
    y = input(‘Enter the second number: ‘)
    print x/y
except ZeroDivisionError:
  print "输入的数字不能为0!"
  
#运行输入:
>>>
Enter the first number: 10
Enter the second number: ‘hello.word‘  #输入非数字

Traceback (most recent call last):
  File "I:\Python27\yichang", line 4, in <module>
    print x/y
TypeError: unsupported operand type(s) for /: ‘int‘ and ‘str‘  #又报出了别的异常信息

好吧!我们可以再加个异常的处理来处理这种情况:

try:
    x = input(‘Enter the first number: ‘)
    y = input(‘Enter the second number: ‘)
    print x/y
except ZeroDivisionError:
    print "输入的数字不能为0!"
except TypeError:           # 对字符的异常处理
  print "请输入数字!"
  
#再来运行:
>>>
Enter the first number: 10
Enter the second number: ‘hello,word‘
请输入数字!

一个块捕捉多个异常

我们当然也可以用一个块来捕捉多个异常:

try:
    x = input(‘Enter the first number: ‘)
    y = input(‘Enter the second number: ‘)
    print x/y
except (ZeroDivisionError,TypeError,NameError):
    print "你的数字不对!"

捕捉全部异常

就算程序处理了好几种异常,比如上面的程序,运行之后,假如我输入了下面的内容呢

>>>
Enter the first number: 10
Enter the second number:   #不输入任何内容,回车

Traceback (most recent call last):
  File "I:\Python27\yichang", line 3, in <module>
    y = input(‘Enter the second number: ‘)
  File "<string>", line 0

   ^
SyntaxError: unexpected EOF while parsing

晕死~! 怎么办呢?总有被我们不小心忽略处理的情况,如果真想用一段代码捕捉所有异常,那么可在except子句中忽略所有的异常类:

try:
    x = input(‘Enter the first number: ‘)
    y = input(‘Enter the second number: ‘)
    print x/y
except:
    print ‘有错误发生了!‘

#再来输入一些内容看看
>>>
Enter the first number: ‘hello‘ * )0
有错误发生了!

结束

别急!再来说说最后一个情况,好吧,用户不小心输入了错误的信息,能不能再给次机会输入?我们可以加个循环,保你输对时才结束:

while True:

    try:
        x = input(‘Enter the first number: ‘)
        y = input(‘Enter the second number: ‘)
        value = x/y
        print ‘x/y is‘,value        break
    except:
        print ‘列效输入,再来一次!‘

#运行
>>>
Enter the first number: 10
Enter the second number:
列效输入,再来一次!
Enter the first number: 10
Enter the second number: ‘hello‘
列效输入,再来一次!
Enter the first number: 10
Enter the second number: 2
x/y is 5

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

温馨提示:因为是学习笔记,尽量精简了文字,所以,你要跟着做才能体会,光看是没用的(也没意思)。

时间: 2024-08-03 20:08:38

python基础教程(九)的相关文章

python基础教程_学习笔记3:元组

元组 元组不能修改:(可能你已经注意到了:字符串也不能修改.) 创建元组的语法很简单:如果用逗号分隔了一些值,那么你就自动创建了元组. >>> 1,3,'ab' (1, 3, 'ab') 元组也是(大部分时候是)通过圆括号括起来的. >>> (1,3,'13') (1, 3, '13') 空元组可以用没有内容的两个圆括号来表示. 如何实现包括一个值的元组呢? >>> (5) 5 >>> ('ab') 'ab' >>>

Python基础教程(第五章 条件、循环和其他语句)

本文内容全部出自<Python基础教程>第二版,在此分享自己的学习之路. ______欢迎转载:http://www.cnblogs.com/Marlowes/p/5329066.html______ Created on Xu Hoo 读者学到这里估计都有点不耐烦了.好吧,这些数据结构什么的看起来都挺好,但还是没法用它们做什么事,对吧? 下面开始,进度会慢慢加快.前面已经介绍过了几种基本语句(print语句.import语句.赋值语句).在深入介绍条件语句和循环语句之前,我们先来看看这几种基

Python基础教程(第九章 魔法方法、属性和迭代器)

本文内容全部出自<Python基础教程>第二版,在此分享自己的学习之路. ______欢迎转载:http://www.cnblogs.com/Marlowes/p/5437223.html______ Created on Marlowes 在Python中,有的名称会在前面和后面都加上两个下划线,这种写法很特别.前面几章中已经出现过一些这样的名称(如__future__),这种拼写表示名字有特殊含义,所以绝不要在自己的程序中使用这样的名字.在Python中,由这些名字组成的集合所包含的方法称

python基础教程(第二版)

开始学习python,根据Python基础教程,把里面相关的基础章节写成对应的.py文件 下面是github上的链接 python基础第1章基础 python基础第2章序列和元组 python基础第3章使用字符串 python基础第4章字典 python基础第5章循环 python基础第6章函数和魔法参数 python基础第7章类 python基础第8章异常 python基础第9章魔法方法.属性和迭代器 python基础第11章文件 python基础第12章GUI(wxPython) pytho

Python基础教程(第十章 自带电池)

本文内容全部出自<Python基础教程>第二版,在此分享自己的学习之路. ______欢迎转载:http://www.cnblogs.com/Marlowes/p/5459376.html______ Created on Marlowes 现在已经介绍了Python语言的大部分基础知识.Python语言的核心非常强大,同时还提供了更多值得一试的工具.Python的标准安装中还包括一组模块,称为标准库(standard library).之前已经介绍了一些模块(例如math和cmath,其中包

python基础教程_学习笔记23:图形用户界面

图形用户界面 丰富的平台 在编写Python GUI程序前,需要决定使用哪个GUI平台. 简单来说,平台是图形组件的一个特定集合,可以通过叫做GUI工具包的给定Python模块进行访问. 工具包 描述 Tkinter 使用Tk平台.很容易得到.半标准. wxpython 基于wxWindows.跨平台越来越流行. PythonWin 只能在Windows上使用.使用了本机的Windows GUI功能. JavaSwing 只能用于Jython.使用本机的Java GUI. PyGTK 使用GTK

python基础教程:第一章

引言 Python是一门计算机能够理解的语言.功能强大,容易入门.是初学者学习编程语言不错的选择.本篇属于python基础知识.简单介绍了变量.函数.模块和字符串的知识. 内容 主要介绍变量.语句.函数.获取用户输入.模块.字符串等知识. 推荐书籍 <python基础教程> <python核心编程>

.Net程序员之Python基础教程学习----列表和元组 [First Day]

一. 通用序列操作: 其实对于列表,元组 都属于序列化数据,可以通过下表来访问的.下面就来看看序列的基本操作吧. 1.1 索引: 序列中的所有元素的下标是从0开始递增的. 如果索引的长度的是N,那么所以的范围是-N~N-1之间,超过这个范围就会提示 IndexError:  index out of range >>> greeting ='Hello world' >>> print greeting Hello world >>> print gr

Python基础教程(第六章 抽象)

本文内容全部出自<Python基础教程>第二版,在此分享自己的学习之路. ______欢迎转载:http://www.cnblogs.com/Marlowes/p/5351415.html______ Created on Xu Hoo 本章将会介绍如何将语句组织成函数,这样,你可以告诉计算机如何做事,并且只需要告诉一次.有了函数以后,就不必反反复复像计算机传递同样的具体指令了.本章还会详细介绍参数(parameter)和作用域(scope)的概念,以及地柜的概念及其在程序中的用途. 6.1

《python基础教程(第二版)》学习笔记 字符串(第3章)

<python基础教程(第二版)>学习笔记 字符串(第3章)所有的基本的序列操作(索引,分片,乘法,判断成员资格,求长度,求最大最小值)对字符串也适用.字符串是不可以改变的:%左侧是格式字符串,右侧是需要格式化的值print '%s=%d' % ('x',100) ==> x=100%% 格式字符串中出现 %模板字符串:from string import Templates=Template('$x is 100');  s.substitute(x='ABC');  ==> '