Python语法基础-异常

前言

推荐文档:https://www.w3school.com.cn/python/index.asp

异常

1
2
3
4
5
6
try:
# 可能会引发异常的代码
result = 10 / 0
except Exception as e:
# 打印异常消息
print(f"发生异常: {e}")

try 块将生成异常,因为 x 未定义:

1
2
3
4
try:
print(x)
except:
print("An exception occurred")

多个异常

您可以根据需要定义任意数量的 exception 块,例如,假如您要为特殊类型的错误执行特殊代码块:

如果 try 块引发 NameError,则打印一条消息,如果是其他错误则打印另一条消息:

1
2
3
4
5
6
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")

Else

如果没有引发错误,那么您可以使用 else 关键字来定义要执行的代码块:

在本例中,try 块不会生成任何错误:

1
2
3
4
5
6
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")

Finally

如果指定了 finally 块,则无论 try 块是否引发错误,都会执行 finally 块。

1
2
3
4
5
6
try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")

with

1
2
3
4
5
6
7
8
9
10
11
try:
f = open('xxx')
except:
print('fail to open')
exit(-1)
try:
do something
except:
do something
finally:
f.close()

虽然这段代码运行良好,但比较冗长。
而使用with的话,能够减少冗长,还能自动处理上下文环境产生的异常。

如下面代码:

1
2
with open("1.txt") as file:
data = file.read()

with 工作原理

(1)紧跟with后面的语句被求值后,返回对象的__enter__()方法被调用,这个方法的返回值将被赋值给as后面的变量;
(2)当with后面的代码块全部被执行完之后,将调用前面返回对象的__exit__()方法。
with工作原理代码示例:

1
2
3
4
5
6
7
8
9
10
class Sample:
def __enter__(self):
print "in __enter__"
return "Foo"
def __exit__(self, exc_type, exc_val, exc_tb):
print "in __exit__"
def get_sample():
return Sample()
with get_sample() as sample:
print "Sample: ",

代码的运行结果如下:

1
2
3
in __enter__
Sample: Foo
in __exit__

可以看到,整个运行过程如下:
(1)enter()方法被执行;
(2)enter()方法的返回值,在这个例子中是”Foo”,赋值给变量sample;
(3)执行代码块,打印sample变量的值为”Foo”;
(4)exit()方法被调用;

exit()方法中有3个参数, exc_type, exc_val, exc_tb,这些参数在异常处理中相当有用。

  • exc_type: 错误的类型
  • exc_val: 错误类型对应的值
  • exc_tb: 代码中错误发生的位置