自定义异常类

class ShortInputException(Exception):
def __init__(self, length, atleast):
Exception.__init__(self)
self.length = length
self.atleast = atleast
try:
s = input('Please Input --> ')
if len(s)<3:
raise ShortInputException(len(s), 3)
except EOFError:
print('You input a end mark EOF')
except ShortInputException as x:
print('ShortInputException: length is {0:,}, at least is {1:,}'.format(x.length, x.atleast))
else:
print('no error and everything is ok.')
Please Input --> yuxingliangEOF
no error and everything is ok.
class MyError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
try:
raise MyError(2*2)
except MyError as e:
print('My exception occurred, value: ', e.value)
My exception occurred, value:  4

0. 断言语句的应用

assert

作用:确认条件表达式是否满足,一般和异常处理结构一起使用。

结构:

assert 条件表达式, '表达式error时,给出此处的判定字符串提示。'

a,b = 3, 5
assert a == b, 'a must be equal to b.' #判定a是否等于b,if a != b,抛出异常
---------------------------------------------------------------------------

AssertionError                            Traceback (most recent call last)

<ipython-input-7-2ad85e920458> in <module>()
1 a,b = 3, 5
----> 2 assert a == b, 'a must be equal to b.' #判定a是否等于b,if a != b,抛出异常 AssertionError: a must be equal to b.
try:
assert a == b, 'a must be equal to b'
except AssertionError as reason:
print('%s:%s'%(reason.__class__.__name__, reason))
AssertionError:a must be equal to b

1. try...except... 结构

  • 如果try子句中的代码引发异常并被except子句捕捉,则执行except子句的代码块;
  • 如果try子句中的代码块没有出现异常,则except子句代码块不执行,继续往后执行。
try:
#可能会引发异常的代码,先执行以下试试看
except:
#如果try中的代码抛出异常并被except捕捉,则执行此处的代码语句
"""代码功能:决策用户输入的是否是一个数字。
代码功能详细描述:while语句主导的死循环。
首先要求用户输入,然后就用户的输入进行判定:
尝试try中的语句
用户输入正确的数字,将输入的数字字符转换成数字,然后打印出提示信息,break掉循环
用户输入错误的字符,try中的语句检测到错误,然后被exception捕捉到,马上转到except中的语句执行,打印错误信息
虽有开始下一步的循环,知道用户输入正确的数字字符,采用break语句终止循环。"""
while True:
x = input('Please input: ')
try:
x = int(x)
print('You have input {0}'.format(x))
break
except Exception as e:
print('Error.')
Please input: a
Error.
Please input: 234f
Error.
Please input: 6
You have input 6

2. try...except...else...结构

try except else
检测语句 有问题,执行相应的处理代码 不执行else语句
检测语句 没问题,不执行except语句 执行else下的语句
try:
#可能会引发错误的代码
except Exception as reason:
#用来处理异常的代码
else:
#如果try中的子句代码没有引发异常,就执行此处的代码
while True:
x = input('Please input: ')
try:
x = int(x) # 此处是可能引发异常的语句
except Exception as e:
print('Error.') # 处理异常的语句
else: # 没有异常时,处理的语句
print('You have input {0}'.format(x))
break
Please input: a
Error.
Please input: b
Error.
Please input: 664h
Error.
Please input: 666
You have input 666

3. try...except...finally...结构

try except finally
尝试语句 有问题,执行相应的处理代码 始终执行finally语句
尝试语句 没问题,不执行except语句 始终执行finally语句
try:
#可能会引发错误的代码
except Exception as reason:
#用来处理异常的代码
finally:
#不论try中是否引发异常,始终执行此处的代码
def div(a,b):
try:
print(a/b)
except ZeroDivisionError:
print('The second parameter cannot be 0.')
finally:
print(-1)
div(3,5)
0.6
-1
div(3,0)
The second parameter cannot be 0.
-1

如果try子句中的异常没有被except语句捕捉和处理,或者except子句或者else子句中的代码抛出的了异常,

那么这些异常将会在finally子句执行完毕之后再次抛出异常。

div('3',5)
-1

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

TypeError                                 Traceback (most recent call last)

<ipython-input-15-dc6751a7464e> in <module>()
----> 1 div('3',5) <ipython-input-12-d5530669db53> in div(a, b)
1 def div(a,b):
2 try:
----> 3 print(a/b)
4 except ZeroDivisionError:
5 print('The second parameter cannot be 0.') TypeError: unsupported operand type(s) for /: 'str' and 'int'

4. 捕捉多种异常的结构

try:
#可能会引发异常的代码
except Exception1:
#处理异常类型1的代码
except Exception2:
#处理异常类型2的代码
except Exception3:
#处理异常类型3的代码
.
.
.
try:
x = float(input('Please the first number: '))
y = float(input('Please the second number: '))
z = x/y
except ZeroDivisionError:
print('the second number isnot 0.')
except TypeError:
print('the number must be number.')
except NameError:
print('The variable isnot here.')
else:
print(x, '/', y, '=', z)
Please the first number: 30
Please the second number: 5
30.0 / 5.0 = 6.0
try:
x = float(input('Please the first number: '))
y = float(input('Please the second number: '))
z = x/y
except (ZeroDivisionError, TypeError, NameError):
print('Error is catched.')
else:
print(x, '/', y, '=', z)
Please the first number: 45
Please the second number: 0
Error is catched.

5. 多种结构混合

def div(x,y):
try:
print(x/y)
except ZeroDivisionError:
print('ZeroDivisionError')
except TypeError:
print('typeerror')
else:
print('no error')
finally:
print('I am executing finally clause.')
div(3,4)
0.75
no error
I am executing finally clause.

Python3基础之异常结构的更多相关文章

  1. python3基础视频教程

    随着目前Python行业的薪资水平越来越高,很多人想加入该行业拿高薪.有没有想通过视频教程入门的同学们?这份Python教程全集等你来学习啦! python3基础视频教程:http://pan.bai ...

  2. Python3基础-特别函数(map filter partial reduces sorted)实例学习

    1. 装饰器 关于Python装饰器的讲解,网上一搜有很多资料,有些资料讲的很详细.因此,我不再详述,我会给出一些连接,帮助理解. 探究functools模块wraps装饰器的用途 案例1 impor ...

  3. 2. Python3 基础入门

    Python3 基础入门 编码 在python3中,默认情况下以UTF-8编码.所有字符串都是 unicode 字符串,当然也可以指定不同编码.体验过2.x版本的编码问题,才知道什么叫难受. # -* ...

  4. python002 Python3 基础语法

    python002 Python3 基础语法 编码默认情况下,Python 3 源码文件以 UTF-8 编码,所有字符串都是 unicode 字符串. 当然你也可以为源码文件指定不同的编码: # -* ...

  5. Python3基础(十二) 学习总结·附PDF

    Python是一门强大的解释型.面向对象的高级程序设计语言,它优雅.简单.可移植.易扩展,可用于桌面应用.系统编程.数据库编程.网络编程.web开发.图像处理.人工智能.数学应用.文本处理等等. 在学 ...

  6. Python3基础(八) 模块

    在程序中定义函数可以实现代码重用.但当你的代码逐渐变得庞大时,你可能想要把它分割成几个文件,以便能够更简单地维护.同时,你希望在一个文件中写的代码能够被其他文件所重用,这时我们应该使用模块(modul ...

  7. 【python3基础】python3 神坑笔记

    目录 os 篇 os.listdir(path) 运算符篇 is vs. == 实例 1:判断两个整数相等 实例 2:argparse 传参 实例 3:np.where 命令行参数篇 Referenc ...

  8. Python3基础语法和数据类型

    Python3基础语法 编码 默认情况下,Python3源文件以UTF-8编码,所有字符串都是unicode字符串.当然你也可以为原码文件制定不同的编码: # -*- coding: 编码 -*- 标 ...

  9. Python3基础-目录

    Python3基础-目录(Tips:长期更新Python3目录) 第一章 初识Python3  1.1 Python3基础-前言  1.2 Python3基础-规范 第二章 Python3内置函数&a ...

随机推荐

  1. 那些IT行业的经典定律

    几十年来,IT界有一些非常著名的定律,蕴含着行业发展的大智慧,非常有趣,略作收集总结,再加上一丁点自己的浅见~ 一.摩尔定律:价格不变,集成电路上可容纳的元器件数目,约每隔18个月便会翻一倍,性能也将 ...

  2. 如何在linux下检测内存泄漏(转)

    本文转自:http://www.ibm.com/developerworks/cn/linux/l-mleak/ 本文针对 linux 下的 C++ 程序的内存泄漏的检测方法及其实现进行探讨.其中包括 ...

  3. springboot系列四、配置模板引擎、配置热部署

    一.配置模板引擎 在之前所见到的信息显示发现都是以 Rest 风格进行显示,但是很明显在实际的开发之中,所有数据的显示最终都应该交由页面完成,但是这个页面并不是*.jsp 页面,而是普通的*.html ...

  4. OA系统高性能解决方案(史上最全的通达OA系统优化方案)

    序: 这是一篇针对通达OA系统的整体优化方案,文档将硬件.网络.linux操作系统.程序本身(包括web和数据库)以及现有业务有效结合在一起,进行了系统的整合优化.该方案应用于真实生产环境,部署完成后 ...

  5. 前端web服务器数据同步方案

    概述: 网站采用了web和mysql数据库分离的架构,前端有web1.web2.web3需要对他们进行上传文件同步 方案: 在web2的windows服务器上安装GoodSync软件,利用其双向同步特 ...

  6. MySQL 数据类型(转)

    MySQL 数据类型 在 MySQL 中,有三种主要的类型:文本.数字和日期/时间类型. Text 类型: 数据类型 描述 备注 CHAR(size) 保存固定长度的字符串(可包含字母.数字以及特殊字 ...

  7. php中相对路径和绝对路径如何使用(详解)

    目录 一.总结 一句话总结: 1.php中用用“/”表示根目录么? 2.什么符号表示当前目录(asp,jsp,php都一样)? 3.php中如何使用$_SERVER['DOCUMENT_ROOT']做 ...

  8. laravel 同数据表字段比较查询和状态不正规排序

    今天写群组推荐接口,要求未满的群 ( 群最大人数字段maxusers, 群人数字段affiliations_count 都在群组表中),官方,热门(普通群0 ,官方1,热门2 ) 排序的群 同表字段比 ...

  9. cf 1041C双指针

    比赛的时候想着用单调队列做... 打完发现其实就是个双指针 /* 构造双指针解决即可 */ #include<iostream> #include<cstring> #incl ...

  10. IDA Pro的patch插件 KeyPatch

    本来这个是没什么可写的,但是安这个插件的时候真是气到爆炸,安装文档写的不明不白,几万行的代码都写了就差那么点时间写个几十字的详细说明吗? 1.下载keypatch.py放到\IDA\plugins里 ...