2023年11月29日发(作者:)
python2和python3的pt...
格式:
try:
pass
except ValueError as e:
pass
except Exception as e:
pass
else:
pass
finally:
pass
try 包含在try下的所有代码块都会进⾏异常检测处理
execpt 处理异常 其后⾯的e(标准故障信息)可以指定也可以不指定
finally 不管是否出现异常都会执⾏其下⾯的代码块
python2
def division(x,y):
if y == 0 :
raise ZeroDivisionError('The zero is not allow')
return x/y
try:
division(1,0)
except ZeroDivisionError, e:
print(e)
python3
def division(x,y):
if y == 0 :
raise ZeroDivisionError('The zero is not allow')
return x/y
try:
division(1,0)
except ZeroDivisionError as e:
print(e)
#The zero is not allow
输出
⾃定义异常类
#_*_coding=UTF-8_*_
#
使⽤⾃定义异常类实现指定输⼊字符串长度
#
⾃定义异常类
class SomeCustomError(Exception):
def __init__(self,str_length):
super(SomeCustomError,self).__init__()
self.str_length = str_length
#
使⽤⾃定义异常
length = input("输⼊指定输⼊字符串长度范围:n")
while True:
try:
s = input("输⼊⼀⾏字符串:n")
#,
输⼊字符串长度超过指定长度范围引发异常
if (int(length) < len(s)):
raise SomeCustomError(int(length))
except SomeCustomError as x:
print("捕获⾃定义异常")
print("输⼊字符串重读应该⼩于%d,请重新输⼊!" % x.str_length)
else:
print("输⼊字符串为%s" % s)
break
测试
输⼊指定输⼊字符串长度范围:
2
输⼊⼀⾏字符串:
sjgx
捕获⾃定义异常
输⼊字符串重读应该⼩于2,请重新输⼊!
输⼊⼀⾏字符串:
dd
输⼊字符串为dd
python标准异常
异常名称描述
BaseException所有异常的基类
SystemExit解释器请求退出
KeyboardInterrupt⽤户中断执⾏(通常是输⼊^C)
Exception常规错误的基类
StopIteration迭代器没有更多的值
GeneratorExit⽣成器(generator)发⽣异常来通知退出
StandardError所有的内建标准异常的基类
ArithmeticError所有数值计算错误的基类
FloatingPointError浮点计算错误
OverflowError数值运算超出最⼤限制
ZeroDivisionError除(或取模)零 (所有数据类型)
AssertionError断⾔语句失败
AttributeError对象没有这个属性
异常名称描述
EOFError没有内建输⼊,到达EOF 标记
EnvironmentError操作系统错误的基类
IOError输⼊/输出操作失败
OSError操作系统错误
WindowsError系统调⽤失败
ImportError导⼊模块/对象失败
LookupError⽆效数据查询的基类
IndexError序列中没有此索引(index)
KeyError映射中没有这个键
MemoryError内存溢出错误(对于Python 解释器不是致命的)
NameError未声明/初始化对象 (没有属性)
UnboundLocalError访问未初始化的本地变量
ReferenceError弱引⽤(Weak reference)试图访问已经垃圾回收了的对象
RuntimeError⼀般的运⾏时错误
NotImplementedError尚未实现的⽅法
SyntaxErrorPython 语法错误
IndentationError缩进错误
TabErrorTab 和空格混⽤
SystemError⼀般的解释器系统错误
TypeError对类型⽆效的操作
ValueError传⼊⽆效的参数
UnicodeErrorUnicode 相关的错误
UnicodeDecodeErrorUnicode 解码时的错误
UnicodeEncodeErrorUnicode 编码时错误
UnicodeTranslateErrorUnicode 转换时错误
Warning警告的基类
DeprecationWarning关于被弃⽤的特征的警告
FutureWarning关于构造将来语义会有改变的警告
OverflowWarning旧的关于⾃动提升为长整型(long)的警告
PendingDeprecationWarning关于特性将会被废弃的警告
RuntimeWarning可疑的运⾏时⾏为(runtime behavior)的警告
SyntaxWarning可疑的语法的警告
UserWarning⽤户代码⽣成的警告


发布评论