自定义异常类

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. android摄像头(camera)之 v4l2的c测试代码【转】

    转自:https://blog.csdn.net/ldswfun/article/details/8745577 在移植android hal的过程中,移植的首要任务是要确保驱动完好,camera是属 ...

  2. llinux除了软连接本地文件夹同步:mount

    mount --bind /srv/dir1   /srv/dir2dir1:被共享的文件夹dir2:需要同步的文件夹

  3. gunicorn+flask使用与配置

    gun.conf的内容 import os bind = '10.1.240.222:5000' workers = 4 backlog = 2048 worker_class = "syn ...

  4. 云服务器 linux文件系统异常an error occurren during the file system check导致服务器启动失败

    云服务器 linux文件系统异常an error occurren during the file system check导致服务器启动失败 文件系统宕机,重启后报错,无法启动 处理流程: 1.编辑 ...

  5. freeswitch用户整合(使用mysql数据库的用户表)

    转:freeswitch用户整合(使用mysql数据库的用户表) freeswitch是一款强大的voip服务器,可以语音和视频.但是它默认是采用/directory文件夹下的xml来配置用户的,对于 ...

  6. 对比synchronized与java.util.concurrent.locks.Lock 的异同

    主要区别 1.Lock能完成几乎所有synchronized的功能,并有一些后者不具备的功能,如公平锁.等待可中断.锁绑定多个条件等: 2.synchronized 是Java 语言层面的,是内置的关 ...

  7. PYTHON-基本数据类型-元祖类型,字典类型,集合类型

    内容: 1. 元组 2. 字典 3. 集合=========================== 元祖类型什么是元组: 元组就是一个不可变的列表============================ ...

  8. Java 开发环境配置--eclipse工具进行java开发

    Java 开发环境配置 在本章节中我们将为大家介绍如何搭建Java开发环境. Windows 上安装开发环境 Linux 上安装开发环境 安装 Eclipse 运行 Java Cloud Studio ...

  9. ie6 表格td中无内容时不显示边框的解决办法

    1.在单元格中加入一个空格.这样: <td> </td> 2.直接在table里这样写:<table border="0" cellspacing=& ...

  10. TestNG配置注解

    以下是TestNG支持的注释列表: 注解 描述 @BeforeSuite 在该套件的所有测试都运行在注释的方法之前,仅运行一次. @AfterSuite 在该套件的所有测试都运行在注释方法之后,仅运行 ...