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

python基础学习笔记(九)的更多相关文章

  1. 0003.5-20180422-自动化第四章-python基础学习笔记--脚本

    0003.5-20180422-自动化第四章-python基础学习笔记--脚本 1-shopping """ v = [ {"name": " ...

  2. Python基础学习笔记(九)常用数据类型转换函数

    参考资料: 1. <Python基础教程> 2. http://www.runoob.com/python/python-variable-types.html 3. http://www ...

  3. python 基础学习笔记(1)

    声明:  本人是在校学生,自学python,也是刚刚开始学习,写博客纯属为了让自己整理知识点和关键内容,当然也希望可以通过我都博客来提醒一些零基础学习python的人们.若有什么不对,请大家及时指出, ...

  4. Python 基础学习笔记(超详细版)

    1.变量 python中变量很简单,不需要指定数据类型,直接使用等号定义就好.python变量里面存的是内存地址,也就是这个值存在内存里面的哪个地方,如果再把这个变量赋值给另一个变量,新的变量通过之前 ...

  5. Python基础学习笔记(十三)异常

    参考资料: 1. <Python基础教程> 2. http://www.runoob.com/python/python-exceptions.html Python用异常对象(excep ...

  6. Python基础学习笔记(十二)文件I/O

    参考资料: 1. <Python基础教程> 2. http://www.runoob.com/python/python-files-io.html ▶ 键盘输入 注意raw_input函 ...

  7. Python基础学习笔记(十一)函数、模块与包

    参考资料: 1. <Python基础教程> 2. http://www.runoob.com/python/python-functions.html 3. http://www.liao ...

  8. Python基础学习笔记(十)日期Calendar和时间Timer

    参考资料: 1. <Python基础教程> 2. http://www.runoob.com/python/python-date-time.html 3. http://www.liao ...

  9. Python基础学习笔记(八)常用字典内置函数和方法

    参考资料: 1. <Python基础教程> 2. http://www.runoob.com/python/python-dictionary.html 3. http://www.lia ...

  10. Python基础学习笔记(七)常用元组内置函数

    参考资料: 1. <Python基础教程> 2. http://www.runoob.com/python/python-tuples.html 3. http://www.liaoxue ...

随机推荐

  1. Centos7查询开机启动项服务

    问题描述: 最近安装了zabbix设置了一些开机启动服务 例如:zabbix-server.service,httpd.service,mariadb.service,或者系统的firework.se ...

  2. 【PAT】B1037 在霍格沃茨找零钱(20 分)

    #include<stdio.h> #include<string.h> #include<algorithm> using namespace std; int ...

  3. git命令行clone指定分支、更新、冲突解决、提交代码步骤

    clone指定分支 : git init 初始化仓库 git clone -b 分支名  git@192.168.3.166:xxxx/xxxx.git   克隆指定分支 更新 :git status ...

  4. Alpha冲刺! Day4 - 磨刀

    Alpha冲刺! Day4 - 磨刀 今日已完成 晨瑶:和大家交流了一下,反思这阶段团队遇到的问题. 昭锡:今天跟学长交流了点问题,学习了Gson使用. 永盛:Gravel 数据库重新设计. 立强:看 ...

  5. 阿里八八β阶段Scrum(1/5)

    今日进度 叶文滔: 修改了α阶段遗留的部分界面BUG,比如状态栏白底等 张岳: 修复用户模块信息修改返回失败的BUG 林炜鸿: 重构了添加事件的代码,增加可修改的特性 黄梅玲: 绘制了新的日程显示格界 ...

  6. mysql字符串查询常用命令

    对于针对字符串位置的操作,第一个位置被标记为1. ASCII(str) 返回字符串str的最左面字符的ASCII代码值.如果str是空字符串,返回0.如果str是NULL,返回NULL. mysql' ...

  7. python之面向对象进阶2

    封装.property装饰器 封装分为3种情况:封装对象的属性.封装类的属性.封装方法. 封装对象的属性:(在属性名前加双下划线__) class Person: def __init__(self, ...

  8. 自己定义控件-DragButton

    版权声明:本文为博主原创文章.欢迎转载,转载请注明博主和原文链接. https://blog.csdn.net/u014077888/article/details/28097273 一.描写叙述 可 ...

  9. 【洛谷】【最小生成树】P1536 村村通

    [题目描述:] 某市调查城镇交通状况,得到现有城镇道路统计表.表中列出了每条道路直接连通的城镇.市政府"村村通工程"的目标是使全市任何两个城镇间都可以实现交通(但不一定有直接的道路 ...

  10. 【转】Kaggle注册问题-验证码和手机短信

    注册和登录Kaggle时验证码无法显示问题 参考:https://blog.csdn.net/zhuisaozhang1292/article/details/81529981 应用FQ软件需要时时关 ...