|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
>>> # try-except 还可以跟 else 进行搭配,它的含义就是当 try 语句没有检测到任何异常的情况下,就执行 else 语句的内容:
>>> try:
... 1 / 0
... except:
... print("逮到了~")
... else:
... print("没逮到..")
...
逮到了~
>>> try:
... 1 / 1
... except:
... print("带到了~")
... else:
... print("没逮到")
...
1.0
没逮到
>>> # 跟 try-except 语句搭配的还有一个 finally,就是说无论异常发生与否,都必须要执行的语句:
>>> try:
... 1 / 0
... except:
... print("逮到了")
... else:
... print("没逮到")
... finally:
... print("逮没逮到都一样!")
...
逮到了
逮没逮到都一样!
>>> # try:
检测范围
except [expression [as identifier]]:
异常处理代码
[except [expression [as identifier]]:
异常处理代码]*
[else:
没有触发异常时执行的代码]
[finally:
收尾工作执行的代码]
>>> # 异常也是可以被嵌套的:
... try:
... 520 + "FishC"
... except:
... print("内部异常!")
... 1 / 0
... except:
... print("外部异常")
... finally:
... print("收尾工作~")
...
内部异常!
外部异常
收尾工作~
>>> # 使用 raise 语句,我们可以手动的引发异常:
>>> raise ValueError("值不正确")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: 值不正确
>>> # 还有一种叫异常链,在 raise 后面加个 from:
>>> raise ValueError("这样可不行") from ZeroDivisionError
ZeroDivisionError
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: 这样可不行
>>> # assert 语句只能引发一个叫 AssertionError 的异常。
>>> s = "FishC"
>>> assert s == "FishC" # 得到期待的结果,通过
>>> assert s != "FishC" # 没有得到期待的结果,引发异常
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError
>>> # 利用异常来实现 goto
>>> try:
... while True:
... while True:
... for i in range(10):
... if i > 3:
... raise
... print(i)
... print("被跳过")
... print("被跳过")
... print("被跳过")
... except:
... print("到这里来")
...
0
1
2
3
到这里来
>>> |
|