1.异常类只能来处理指定的异常情况,如果非指定异常则无法处理
s1 = 'hello'
try:
int(s1)
except IndexError as e: # 未捕获到异常,程序直接报错
print (e)
2.多分支
s1 = 'hello'
try:
int(s1)
except IndexError as e:
print(e)
except KeyError as e:
print(e)
except ValueError as e:
print(e)
3.万能异常Exception
s1 = 'hello'
try:
int(s1)
except Exception as e:
print(e)
4.多分支+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)
5.异常的其他机构(try…finally语法)
try:
<语句>
finally:
<语句> #退出try时总会执行
raise
#Python学习交流QQ群:725638078
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('无论异常与否,都会执行该模块,通常是进行清理工作')
6.主动触发异常(raise语句)
raise [Exception [, args [, traceback]]]
def functionName( level ):
if level < 1:
raise Exception("Invalid level!", level)
# 触发异常后,后面的代码就不会再执行
try:
raise TypeError('类型错误')
except Exception as e:
print(e)
7.自定义异常
class Networkerror(BaseException):
def __init__(self,msg):
self.msg=msg
def __str__(self):
return self.msg
try:
raise Networkerror('类型错误')
except Networkerror as e:
print(e)
8.断言:assert条件
assert 1 == 1
assert 1 == 2
发表评论