0910--https://www.cnblogs.com/fnng/archive/2013/04/28/3048356.html

Python异常

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

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

raise语句

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

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

系统自带的内建异常类:

自定义异常

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

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

>>> class someCustomException(Exception):pass

捕捉异常

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

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

try:
x = int(input('Enter the first number:'))
y = int(input('Enter the sencond number:'))
z = x/y
print(z)
except ZeroDivisionError:
print('输入的数字不能为0!') #输入
Enter the first number:1
Enter the sencond number:0
输入的数字不能为0!

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

class MuffledCalulator:
muffled = False #这里默认关闭屏蔽
def calc(self,expr):
try:
return eval(expr)
except ZeroDivisionError:
if self.muffled:
print ('Division by zero is illegal')
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 = int(input('Enter the first number:'))
y = int(input('Enter the sencond number:'))
z = x/y
print(z)
except ZeroDivisionError:
print('输入的数字不能为0!')
except ValueError:
print('请输入数字')
#运行程序
Enter the first number: 10
Enter the second number: 'hello,word'
请输入数字!

一个块获取多个异常

try:
x = int(input('Enter the first number:'))
y = int(input('Enter the second number:'))
print(x/y)
except (ZeroDivisionError,TypeError,NameError,ValueError):
print("输入的内容有误,请输入非0数字!")
#运行程序
Enter the first number:1
Enter the second number:0
输入的内容有误,请输入非0数字!
#输入非数字
Enter the first number:a
输入的内容有误,请输入非0数字!

捕捉全部异常

就算以上处理了好几种异常,总有不小心忽略处理的情况,如果真想用一段代码捕捉所有异常,那么可在except子句中忽略所有的异常类:

try:
x = int(input('Enter the first number:'))
y = int(input('Enter the second number:'))
print (x/y)
except:
print ('Sorry,Please enter again!')
#运行程序
Enter the first number:1
Enter the second number:djfjshfjkd
Sorry,Please enter again!

加入循环,若用户输入了错误信息,允许重新输入

while True:
try:
x = int(input('Enter the first number:'))
y = int(input('Enter the second number:'))
value = x/y
print ('x/y is',value)
break
except:
print ('输入的内容无效,请重新输入!')
#执行程序
Enter the first number:a
输入的内容无效,请重新输入!
Enter the first number:
输入的内容无效,请重新输入!
Enter the first number:1
Enter the second number:0
输入的内容无效,请重新输入!
Enter the first number:1
Enter the second number:3
x/y is 0.3333333333333333

python学习记录(八)的更多相关文章

  1. Python学习记录day5

    title: Python学习记录day5 tags: python author: Chinge Yang date: 2016-11-26 --- 1.多层装饰器 多层装饰器的原理是,装饰器装饰函 ...

  2. Python学习记录day6

    title: Python学习记录day6 tags: python author: Chinge Yang date: 2016-12-03 --- Python学习记录day6 @(学习)[pyt ...

  3. python学习第八讲,python中的数据类型,列表,元祖,字典,之字典使用与介绍

    目录 python学习第八讲,python中的数据类型,列表,元祖,字典,之字典使用与介绍.md 一丶字典 1.字典的定义 2.字典的使用. 3.字典的常用方法. python学习第八讲,python ...

  4. Python学习记录day8

    目录 Python学习记录day8 1. 静态方法 2. 类方法 3. 属性方法 4. 类的特殊成员方法 4.1 __doc__表示类的描述信息 4.2 __module__ 和 __class__ ...

  5. Python学习记录day7

    目录 Python学习记录day7 1. 面向过程 VS 面向对象 编程范式 2. 面向对象特性 3. 类的定义.构造函数和公有属性 4. 类的析构函数 5. 类的继承 6. 经典类vs新式类 7. ...

  6. Python学习记录:括号配对检测问题

    Python学习记录:括号配对检测问题 一.问题描述 在练习Python程序题的时候,我遇到了括号配对检测问题. 问题描述:提示用户输入一行字符串,其中可能包括小括号 (),请检查小括号是否配对正确, ...

  7. 实验楼Python学习记录_挑战字符串操作

    自我学习记录 Python3 挑战实验 -- 字符串操作 目标 在/home/shiyanlou/Code创建一个 名为 FindDigits.py 的Python 脚本,请读取一串字符串并且把其中所 ...

  8. 我的Python学习记录

    Python日期时间处理:time模块.datetime模块 Python提供了两个标准日期时间处理模块:--time.datetime模块. 那么,这两个模块的功能有什么相同和共同之处呢? 一般来说 ...

  9. Python 学习记录

    记录一些 学习python 的过程 -------------------------------------- 1. 初始学习 @2013年10月6日 今天开始学习python 了 遇到好多困难但是 ...

随机推荐

  1. 「CH2501」 矩阵距离 解题报告

    CH2501 矩阵距离 描述 给定一个N行M列的01矩阵 A,\(A[i][j]\) 与 \(A[k][l]\) 之间的曼哈顿距离定义为: \(dist(A[i][j],A[k][l])=|i-k|+ ...

  2. 变量的取用与设定:echo,变量设定规则,unset

    1.变量的取用echo echo $variable echo ${variable} 2.变量的设定规则 3.让我设定的name=VBird应用在下个应用程序 4.进入到核心的模块目录 5.取消设定 ...

  3. 7个效果震憾的HTML5应用组件

    在HTML5的世界里,任何文本.图像都可以变得令人难以想象,很多HTML5应用也都已经随着浏览器的升级而变得运行飞速,而且兼容性也越来越好.下面为大家介绍7款效果震憾的HTML5应用组件,HTML5是 ...

  4. Scala实践14

    1.Scala的future 创建future import scala.concurrent._ import ExecutionContext.Implicits.global object Fu ...

  5. python列表(数组)

    列表(list)  就是 数组 - 列表是Python中的一个对象 - 对象(object)就是内存中专门用来存储数据的一块区域 - 之前我们学习的对象,像数值,它只能保存一个单一的数据 - 列表中可 ...

  6. 初探ASP.NET Core 3.x (3) - Web的运作流程和ASP.NET Core的运作结构

    本文地址:https://www.cnblogs.com/oberon-zjt0806/p/12215717.html 注意:本篇大量地使用了mermaid绘制图表,加载需要较长的时间,请见谅 [TO ...

  7. 在Vue+element 开发中报: The template root requires exactly one elemen 错的解决和原因

    一.我正准备使用Vue + Element进行新的项目开发,然后在进行添加下一个组件时报错  二.解决及原因: 原来template中只允许模板里存在一个根节点,在 template 中添加一个 &l ...

  8. 提高开发效率的一些ipython技巧

    目录 一.显示ipython快速参考 二.书签功能 三.查看帮助或信息 四.执行python程序 五.执行剪贴板中的代码 六.与操作系统交互 七.测试代码执行时间 八.性能分析 九.matplotli ...

  9. Nginx配置不同端口号映射二级域名

    upstream xx{ #ip_hash; server 127.0.0.1:1008; } server { listen 80; server_name xx.xxx.com; location ...

  10. .net mvc Bundle 自己配置

    遇到了个坑 来和大家分享一下 1.一个空的mvc项目需要引用 System.Web.Optimization 2.然后nuget添加 microsoft ASP.NET WEB OPTIMIZATIO ...