Python3基础之异常结构
自定义异常类
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基础之异常结构的更多相关文章
- python3基础视频教程
随着目前Python行业的薪资水平越来越高,很多人想加入该行业拿高薪.有没有想通过视频教程入门的同学们?这份Python教程全集等你来学习啦! python3基础视频教程:http://pan.bai ...
- Python3基础-特别函数(map filter partial reduces sorted)实例学习
1. 装饰器 关于Python装饰器的讲解,网上一搜有很多资料,有些资料讲的很详细.因此,我不再详述,我会给出一些连接,帮助理解. 探究functools模块wraps装饰器的用途 案例1 impor ...
- 2. Python3 基础入门
Python3 基础入门 编码 在python3中,默认情况下以UTF-8编码.所有字符串都是 unicode 字符串,当然也可以指定不同编码.体验过2.x版本的编码问题,才知道什么叫难受. # -* ...
- python002 Python3 基础语法
python002 Python3 基础语法 编码默认情况下,Python 3 源码文件以 UTF-8 编码,所有字符串都是 unicode 字符串. 当然你也可以为源码文件指定不同的编码: # -* ...
- Python3基础(十二) 学习总结·附PDF
Python是一门强大的解释型.面向对象的高级程序设计语言,它优雅.简单.可移植.易扩展,可用于桌面应用.系统编程.数据库编程.网络编程.web开发.图像处理.人工智能.数学应用.文本处理等等. 在学 ...
- Python3基础(八) 模块
在程序中定义函数可以实现代码重用.但当你的代码逐渐变得庞大时,你可能想要把它分割成几个文件,以便能够更简单地维护.同时,你希望在一个文件中写的代码能够被其他文件所重用,这时我们应该使用模块(modul ...
- 【python3基础】python3 神坑笔记
目录 os 篇 os.listdir(path) 运算符篇 is vs. == 实例 1:判断两个整数相等 实例 2:argparse 传参 实例 3:np.where 命令行参数篇 Referenc ...
- Python3基础语法和数据类型
Python3基础语法 编码 默认情况下,Python3源文件以UTF-8编码,所有字符串都是unicode字符串.当然你也可以为原码文件制定不同的编码: # -*- coding: 编码 -*- 标 ...
- Python3基础-目录
Python3基础-目录(Tips:长期更新Python3目录) 第一章 初识Python3 1.1 Python3基础-前言 1.2 Python3基础-规范 第二章 Python3内置函数&a ...
随机推荐
- UML和模式应用4:初始阶段(6)--迭代方法中如何使用用例
1.前言 用例是UP和其他众多迭代方法的核心.UP提倡用例驱动开发. 2. 迭代方法中如何使用用例 功能需求首先定义在用例中 用例是迭代计划的重要部分,迭代是通过选择一些用例场景或整个用例来定义的 用 ...
- Libevent源码分析—event_add()
接下来就是将已经初始化的event注册到libevent的事件链表上,通过event_add()来实现,源码位于event.c中. event_add() 这个函数主要完成了下面几件事: 1.将eve ...
- flask_restplus(1)- 未完成
快速开始 本指南假设您对Flask有一定的了解,并且您已经安装了Flask和Flask- restplus.如果没有,则按照安装部分中的步骤操作. 初始化 与其他所有扩展一样,您可以使用应用程序对象初 ...
- angular下载安装
1.下载安装nodejs 官方地址:https://nodejs.org/en/download/ 2.验证是否安装成功 node -v npm -v 公司内网需要设置代理 npm confi ...
- [bzoj3123][洛谷P3302] [SDOI2013]森林(树上主席树+启发式合并)
传送门 突然发现好像没有那么难……https://blog.csdn.net/stone41123/article/details/78167288 首先有两个操作,一个查询,一个连接 查询的话,直接 ...
- @PathVariable和@RequestParam
@PathVariable 当使用@RequestMapping URI template 样式映射时, 即 someUrl/{paramId}, 这时的paramId可通过 @Pathvariabl ...
- lnmp环境下piwiki网站流量分析工具的安装及配置
piwiki统计网站的安装 Piwik是一个PHP和MySQL的开放源代码的Web统计软件. 它给你一些关于你的网站的实用统计报告,比如网页浏览人数, 访问最多的页面, 搜索引擎关键词等等- Piwi ...
- zabbix系列(七)zabbix3.0添加对tcp连接数及状态的监控
原理: netstat -an|awk '/^tcp/{++S[$NF]}END{for(a in S) print a,S[a]}' TIME_WAIT 79 ESTABLISHED 6 LISTE ...
- PHP获取网卡的MAC地址原码;目前支持WIN/LINUX系统 获取机器网卡的物理(MAC)地址
声明转换于其它博客当中的. <?php /** 获取网卡的MAC地址原码:目前支持WIN/LINUX系统 获取机器网卡的物理(MAC)地址 **/ class GetMacAddr{ var $ ...
- urllib处理包的简单使用
我们可以使用urllib.request.urlopen()这个接口函数就可以打开一个网站,读取打印信息 你可以现在终端使用python from urllib import request if _ ...