初探异常

什么是异常与异常处理

  • 异常就是错误
  • 异常会导致程序崩溃并停止运行
  • 能监控并捕获异常,将异常部位的程序进行修理使得程序继续正常运行

异常的语法结构

1
2
3
4
5
try
<代码块1> 被try关键字检查并保护的业务代码

except <异常的类型>:
<代码块2> # 代码块1 出现错误后执行的代码块

捕获通用异常

  • 无法确定是哪种异常的情况下使用的捕获方法
1
2
3
4
try:
<代码块>
except Exception as e: # 单词首字母大写
<异常代码块>

捕获具体异常

  • 确定是哪种异常的情况下使用的捕获方法
  • except <具体的异常类型>as e

捕获多个异常(1)

1
2
3
4
5
6
7
8
try:
print('try start')
res = 1/0
print('try finish')
except ZeroDivisionError as e:
print(e)
except Exception as e: #可以有多个except
print(‘this is a public excpet , bug is: %s' % e)
  • except代码块有多个的时候,捕获到第一个后,不会继续向下捕获

捕获多个异常(2)

1
2
3
4
5
6
try:
print('try start')
res = 1/0
print('try finish')
except (ZeroDivisionError, Exception) as e:
print(e)
  • except代码后边的异常类型使用元组包裹起来,捕获到哪种抛出哪种

代码

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
31
32
33
34
35
36
37
38
# coding:utf-8

def upper(str_data):
new_str = 'None'
try:
new_str = str_data.upper()
except Exception as e:
print('程序出错了:{}'.format(e))
return new_str


result = upper(1)
print('result:', result)

def test():
try:
print('123')
1 / 0
print('hello')
except ZeroDivisionError as e:
print(e)


test()


def test1():
try:
print('hello')
print(name)
except (ZeroDivisionError, NameError) as e:
print(e)
print(type(e))
print(dir(e))


test1()