1、什么是异常#
异常通常是指因各种原因的出错程序代码不能正常运行,从而返回报错信息,中断程序。
报错信息由两部分组成(1)Traceback:追溯出错的源头(2)异常所属的类,以及提示的上下文。
1
2
3
4
5
6
|
1/0
#Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# ZeroDivisionError: division by zero
#如上:异常属于ZeroDivisionError,并使用默认的上下文提示division by zero
|
- 常见的异常类都属于
Exception
这个父类,而具体的一些异常类型由它继承而来,一般为****Error
2、捕捉异常#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
##(1) 预知会出现指定类型的错误,并使用默认的上下文提示异常信息
try:
x = 1
y = 0
print(x/y)
except ZeroDivisionError as e:
print(e)
# division by zero
##(2) 预知会出现指定类型的错误,并自定义提示信息
try:
x = 1
y = 0
print(x/y)
except ZeroDivisionError:
print("The second number cannot be zero!")
# The second number cannot be zero!
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
##(1) 使用多个except语句
try:
x = 1
y = "aaaa"
print(x/y)
except ValueError as e:
print(e)
except ZeroDivisionError as e:
print(e)
except TypeError as e:
print(e)
# unsupported operand type(s) for /: 'int' and 'str'
##(2) 使用元组囊括多种异常类别
try:
x = 1
y = "aaaa"
print(x/y)
except (ValueError, ZeroDivisionError, TypeError) as e:
print(e)
# unsupported operand type(s) for /: 'int' and 'str'
##(3) 仅使用except语句,直接捕捉所有异常事件
try:
x = 1
y = 0
print(x/y)
except:
print("Something wrong happened!")
# Something wrong happened!
|
3、搭配其它语句#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
##(1) raise语句:触发指定类型错误,中断程序执行
def calc(number1, number2, muffled=False):
'muffled参数设置为:是否捕捉异常'
try:
print(number1/number2)
except ZeroDivisionError:
if muffled:
print("The second number cannot be zero! But you can go on")
else:
raise ZeroDivisionError("The second number cannot be zero! You are stopped")
calc(1,0, muffled=True)
#The second number cannot be zero! But you can go on
calc(1,0, muffled=False)
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# File "<stdin>", line 9, in calc
# ZeroDivisionError: The second number cannot be zero! You are stopped
##(2) else语句:类似if-else语句,如果没报错....
try:
x = 10
y = 1
z = x/y
except Exception as e:
print(e)
else:
print("The number you provied is good. And the result is", z)
# The number you provied is good. And the result is 10.0
|