标签:base 完成 ESS div 处理 断言 not float 容错性
语法错误,根本过不了python解释器的语法检测,必须在程序执行前就改正。
# 语法错误示范一
if
# 语法错误示范二
def test:
pass
# 语法错误示范三
class Foo
pass
# 语法错误示范四
print(ha
# TypeError:int类型不可迭代
for i in 3:
pass
# ValueError
num = input(">>: ") #输入hello
int(num)
# NameError
aaa
# IndexError
l = ['lh','aa']
l[3]
# KeyErroe
dic = {'name':'nick'}
dic['age']
# AttributeError
class Foo:pass
Foo.x
# ZeroDivisionError:无法完成计算
res1 = 1/0
res2 = 1+'str'
在python中不同的异常可以用不同的类型(python中统一了类与类型,类型即类)去标识,一个异常标识一种错误。
为了保证程序的健壮性与容错性,即在遇到错误时程序不会崩溃,我们需要对异常进行处理
如果错误发生的条件是可预知的,我们需要用if进行处理:在错误发生之前进行预防
AGE = 10
while True:
age = input('-->: ').strip()
if age.isdigit(): # 只有在gae位字符串形式的整数时,下列代码才不会出错,该条件是可预见的
age = int(age)
if age == AGE:
print('you got it')
break
-->: 123
-->: qwe
-->: asd
-->: 10
you got it
如果错误发生的条件是不可预知的,则需要用到try...except:在错误发生之后进行处理
# 基本语法为
try:
被检测的代码块
except 异常类型:
try中一旦检测到异常,就执行这给位置的逻辑
# 举例
try:
f = [
'a',
'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()
a
a
a
a
a
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)
invalid literal for int() with base 10: ‘hello‘
s1 = 'hello'
try:
int(s1)
except Exception as e:
print(e)
如果你想要的效果是,无论出现什么异常,我们统一丢弃,或者使用同一段代码逻辑去处理他们,那么骚年,大胆的去做吧,只有一个Exception就足够了。
如果你想要的效果是,对于不同的异常我们需要定制不同的处理逻辑,那就需要用到多分支了。
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)
s1 = 'hello'
try:
int(s1)
except IndexError as e:
print(e)
except keyError as e:
print(e)
except ValueError as e:
print(e)
else:
print('try内代码块没有异常则执行我')
finally:
print('无论异常与否,都回执行该模块,通常是进行清理工作')
try:
raise TypeError('抛出异常,类型错误')
except Exception as e:
print(e)
5.1 自定义异常
class EgonException(BaseException):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
try:
raise EgonException('抛出异常,类型错误')
except EgonException as e:
print(e)
assert 1 == 1
try:
assert 1 == 2
except Exception as e:
print(e)
标签:base 完成 ESS div 处理 断言 not float 容错性
原文地址:https://www.cnblogs.com/Lin2396/p/11525425.html