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 ...
随机推荐
- 扫AR
- linux暂停一个在运行中的进程【转】
转自:https://blog.csdn.net/Tim_phper/article/details/53536621 转载于: http://www.cszhi.com/20120328/linux ...
- php 日期格式转换万能公式
思路用strtotime转换时间的字符串 $t='2017-03-09 02:30'; echo(date('Y-m-d H-i', strtotime($t)));
- kafka系列五、kafka常用java API
引入maven包 <dependency> <groupId>org.apache.kafka</groupId> <artifactId>kafka- ...
- tomcat8配置SSL
参考网址:http://www.micmiu.com/enterprise-app/sso/sso-cas-sample/#viewSource 1.生成证书 keytool -genkey -ali ...
- C#面向对象(继承)
- 搭建ssh框架项目(一)
一.创建web项目 二.导入jar包 三.创建数据库(MySQL) 四.建立javaBean对象(ElecText.java),属于持久层对象(PO对象) package com.cppdy.ssh. ...
- wpf 自定义属性的默认值
public int MaxSelectCount { get { return (int)GetValue(MaxSelectCountProperty); } set { SetValue(Max ...
- 【python】xsspider零碎知识点
1.提取url信息 urlparse() from urlparse import urlparse url = "http://scrapy-chs.readthedocs.io/zh_C ...
- Iterator 接口
首先要从foreach说起,我们都知道对象,数组和对象可以被foreach语法遍历,数字和字符串却不行.其实除了数组和对象之外PHP内部还提供了一个 Iterator 接口,实现了Iterator接口 ...