Python 官方文档:入门教程 => 点击学习
目录一、什么是异常二、异常的种类1 、常用异常类2、异常举例:三、异常处理1、基本语法try...except2、多分支异常 except..except与万能异常:Exceptio
在python中,错误触发的异常如下
在Python中不同的异常可以用不同的类型去标识,一个异常标识一种错误。
# TypeError:int类型不可迭代
for i in 3:
pass
# ValueError
num=input(">>: ") #输入hello
int(num)
# NameError
aaa
# IndexError
l=['eGon','aa']
l[3]
# KeyError
dic={'name':'egon'}
dic['age']
# AttributeError
class Foo:pass
Foo.x
# ZeroDivisionError:无法完成计算
res1=1/0
res2=1+'str'
try:
被检测的代码块
except 异常类型:
try中一旦检测到异常,就执行这个位置的逻辑
举例
try:
f = [ 'a', 'a', 'a','a','a', 'a','a',]
g = (line.strip() for line in f) #元组推导式
print(next(g))
print(next(g))
print(next(g))
print(next(g))
print(next(g))
except StopIteration:
f.close()
异常类只能用来处理指定的异常情况,如果非指定异常则无法处理。
s1 = 'hello'
try:
int(s1)
except IndexError as e: # 未捕获到异常,程序直接报错
print(e)
s1 = 'hello'
try:
int(s1)
except IndexError as e:
print(e)
except KeyError as e:
print(e)
except ValueError as e:
print(e)
except Exception as e:
print(e)
try/except 语句还有一个可选的 else 子句,如果使用这个子句,那么必须放在所有的 except 子句之后。
else 子句将在 try 子句没有发生任何异常的时候执行。
for arg in sys.argv[1:]:
try:
f = open(arg, 'r')
except IOError:
print('cannot open', arg)
else:
print(arg, 'has', len(f.readlines()), 'lines')
f.close()
try-finally 语句无论是否发生异常都将执行最后的代码。
定义清理行为:
s1 = 'hello'
try:
int(s1)
except IndexError as e:
print(e)
except KeyError as e:
print(e)
except ValueError as e:
print(e)
#except Exception as e:
# print(e)
else:
print('try内代码块没有异常则执行我')
finally:
print('无论异常与否,都会执行该模块,通常是进行清理工作')
#invalid literal for int() with base 10: 'hello'
#无论异常与否,都会执行该模块,通常是进行清理工作
Python 使用 raise 语句抛出一个指定的异常。
raise语法格式如下:
raise [Exception [, args [, traceback]]]
try:
raise TypeError('抛出异常,类型错误')
except Exception as e:
print(e)
raise 唯一的一个参数指定了要被抛出的异常。它必须是一个异常的实例或者是异常的类(也就是 Exception 的子类)。
如果你只想知道这是否抛出了一个异常,并不想去处理它,那么一个简单的 raise 语句就可以再次把它抛出。
try:
raise NameError('HiThere')
except NameError:
print('An exception flew by!')
raise
#An exception flew by!
#Traceback (most recent call last):
# File "", line 2, in ?
#NameError: HiThere
你可以通过创建一个新的异常类来拥有自己的异常。异常类继承自 Exception 类,可以直接继承,或者间接继承,例如:
在这个例子中,类 Exception 默认的 __init__() 被覆盖。
class EgonException(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
try:
raise EgonException('抛出异常,类型错误')
except EgonException as e:
print(e)
#抛出异常,类型错误
当创建一个模块有可能抛出多种不同的异常时,一种通常的做法是为这个包建立一个基础异常类,然后基于这个基础类为不同的错误情况创建不同的子类:
大多数的异常的名字都以"Error"结尾,就跟标准的异常命名一样。
class Error(Exception):
"""Base class for exceptions in this module."""
pass
class InputError(Error):
"""Exception raised for errors in the input.
Attributes:
expression -- input expression in which the error occurred
message -- explanation of the error
"""
def __init__(self, expression, message):
self.expression = expression
self.message = message
class TransitionError(Error):
"""Raised when an operation attempts a state transition that's not
allowed.
Attributes:
previous -- state at beginning of transition
next -- attempted new state
message -- explanation of why the specific transition is not allowed
"""
def __init__(self, previous, next, message):
self.previous = previous
self.next = next
self.message = message
assert(断言)用于判断一个表达式,在表达式条件为 false 的时候触发异常。
断言可以在条件不满足程序运行的情况下直接返回错误,而不必等待程序运行后出现崩溃的情况。
语法格式如下:
assert expression
等价于:
if not expression:
raise AssertionError
assert 后面也可以紧跟参数:
assert expression [, arguments]
等价于:
if not expression:
raise AssertionError(arguments)
以下实例判断当前系统是否为 linux,如果不满足条件则直接触发异常,不必执行接下来的代码:
--结束END--
本文标题: Python中的异常处理讲解
本文链接: https://www.lsjlt.com/news/118379.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0