语法:
try:
可能发生的错误代码
except:
如果出现异常执行的代码
例子:
try:
open("test2.txt", "r", encoding="UTF-8")
except:
print("出现异常,文件不存在,换个模式打开")
open("test2.txt", "w", encoding="UTF-8")
语法:
try:
可能发生的错误代码
except 异常名字 as e:
如果出现异常执行的代码
例子:
try:
print(name)
# 1 / 0
except NameError as e:
print("捕获指定异常")
语法:
try:
可能发生的错误代码
except (异常名字1,异常名字2) as e:
如果出现异常执行的代码
例子:
try:
1 / 0
except (NameError, ZeroDivisionError) as e:
print("捕获多个指定异常")
语法:
try:
可能发生的错误代码
except Exception as e:
如果出现异常执行的代码
例子:
try:
1 / 0
except Exception as e:
print("捕获所有异常")
语法:
try:
可能发生的错误代码
except Exception as e:
如果出现异常执行的代码
else:
没有异常执行的代码
例子:
try:
open("test.txt", "r", encoding="UTF-8")
except Exception as e:
print("出现异常了")
else:
print("没有异常")
语法:
try:
可能发生的错误代码
except Exception as e:
如果出现异常执行的代码
finally:
无论是否有异常都要执行的代码
例子:
try:
f = open("test.txt", "r", encoding="UTF-8")
except Exception as e:
print("出现异常了")
f = open("test.txt", "w", encoding="UTF-8")
else:
print("没有异常")
finally:
f.close()
例子:
def func01():
print("1-1")
num = 1/0
print("1-2")
def func02():
print("2-1")
func01()
print("2-2")
def main():
print("3-1")
try:
func02()
except Exception as e:
print(e)
print("3-2")
main()