1.初识异常

1.1.什么是异常与异常处理

1.2.异常的语法

python常见问题及解决方法(python错误异常怎么解决)(1)

python常见问题及解决方法(python错误异常怎么解决)(2)

1 # coding:utf-8
 2 
 3 def upper(str_data):
 4     new_str='None'
 5     try:
 6         new_str=str_data.upper()
 7     except:
 8         print('程序出错了')
 9     return new_str
10 
11 result=upper(123)
12 print(result)
13 '''
14 程序出错了
15 None
16 '''

1.3.捕获通用异常

python常见问题及解决方法(python错误异常怎么解决)(3)

1 # coding:utf-8
 2 
 3 def upper(str_data):
 4     new_str='None'
 5     try:
 6         new_str=str_data.upper()
 7     except Exception as e:
 8         print('程序出错了:{}'.format(e))
 9     return new_str
10 
11 result=upper(123)
12 print(result)
13 '''
14 程序出错了:'int' object has no attribute 'upper'
15 None
16 '''

1.4.捕获具体异常

python常见问题及解决方法(python错误异常怎么解决)(4)

1 # coding:utf-8
 2 
 3 def test():
 4     try:
 5         print("try start")
 6         1/0
 7         print("try finish") #这句代码不会执行,因为1/0已经报错了,直接进入到exception中了
 8     except ZeroDivisionError as e:
 9         print(e)
10 test()
11 '''
12 try start
13 division by zero
14 '''
1 # coding:utf-8
 2 
 3 def test():
 4     try:
 5         print("try start")
 6         print(name)
 7         print("try finish")
 8     except ZeroDivisionError as e:      #except捕获的异常要与实际发生的异常一致,才能捕获到,不然没有用;捕获的是1/0的报错,实际发生的错误是name变量未定义
 9         print(e)
10 test()
11 '''
12 Traceback (most recent call last):
13   File "D:/WorkSpace/Python_Study/test01.py", line 10, in <module>
14     test()
15   File "D:/WorkSpace/Python_Study/test01.py", line 6, in test
16     print(name)
17 NameError: name 'name' is not defined
18 try start
19 '''

1.5.捕获多个异常

python常见问题及解决方法(python错误异常怎么解决)(5)

python常见问题及解决方法(python错误异常怎么解决)(6)

2.python内置异常函数

异常类型集合

异常名称

说明

Exception

通用异常类型(基类)

ZeroDivisionError

不能整除0

AttributeError

对象没有这个属性

IOError

输入输出操作失败

IndexError

没有当前的索引

KeyError

没有这个键值(key)

NameError

没有这个变量(未初始化对象)

SyntaxError

Python语法错误

SystemError

解释器的系统错误

VauleError

传入的参数错误

3.异常中的finally

finally的功能:

1 # coding:utf-8
 2 
 3 def test():
 4     try:
 5         return "try"
 6     except:
 7         return "except"
 8     finally:
 9         return "finally"
10     
11 print(test())       #finally

4.自定义异常

4.1.自定义抛出异常raise

raise:将信息以报错的形式抛出

python常见问题及解决方法(python错误异常怎么解决)(7)

python常见问题及解决方法(python错误异常怎么解决)(8)

1 # coding:utf-8
 2 
 3 def test(number):
 4     if number==100:
 5         raise ValueError("number不能等于100")
 6     return number
 7 print(test(50))         #50
 8 print(test(100))
 9 '''
10 Traceback (most recent call last):
11   File "D:/WorkSpace/Python_Study/test01.py", line 8, in <module>
12     print(test(100))
13   File "D:/WorkSpace/Python_Study/test01.py", line 5, in test
14     raise ValueError("number不能等于100")
15 ValueError: number不能等于100
16 '''
1 # coding:utf-8
 2 
 3 # 知识点1:raise主动抛出的异常可以被正常捕获
 4 def test(number):
 5     if number==100:
 6         raise ValueError("number不能等于100")
 7     return number
 8 
 9 def test1(number):
10     try:
11         return test(number)
12     except ValueError as e:
13         return e
14 
15 print(test1(100))       #number不能等于100
1 # coding:utf-8
 2 
 3 # 知识点2:raise语法后面没有进行异常类型的传递,直接跟字符串,编译器报错,必须得加,如果不知道异常类型,使用基类Exception
 4 def test():
 5     raise "报错了"
 6 
 7 print(test())
 8 '''
 9 Traceback (most recent call last):
10   File "D:/WorkSpace/Python_Study/test01.py", line 7, in <module>
11     print(test())
12   File "D:/WorkSpace/Python_Study/test01.py", line 5, in test
13     raise "报错了"
14 TypeError: exceptions must derive from BaseException
15 '''

4.2.自定义异常类

python常见问题及解决方法(python错误异常怎么解决)(9)

1 # coding:utf-8
 2 
 3 class NumberLimitError(Exception):
 4     def __init__(self,message):
 5         self.message = message
 6 
 7 class NameLimitError(Exception):
 8     def __init__(self,message):
 9         self.message = message
10 
11 def test(name):
12     if name=="张三":
13         raise NameLimitError("张三不可以被填写")
14     return name
15 
16 def test1(number):
17     if number > 100:
18         raise NumberLimitError("数字不能大于100")
19     return number
20 
21 try:
22     test("张三")
23 except NameLimitError as e:
24     print(e)
25 '''
26 张三不可以被填写
27 '''
28 
29 try:
30     test1(105)
31 except NumberLimitError as e:
32     print(e)
33 '''
34 数字不能大于100
35 '''

5.断言

5.1.断言的功能---assert

assert断言:用于判断一个表达式,在表达式条件为false时触发异常

5.2.断言得用法---assert

python常见问题及解决方法(python错误异常怎么解决)(10)

python常见问题及解决方法(python错误异常怎么解决)(11)

1 # coding:utf-8
 2 
 3 def test(name):
 4     assert name in ["张三","李四"],"{}不在学生列表中".format(name)
 5     print("{}在学生列表中".format(name))
 6 test("张三")      #张三在学生列表中
 7 test("王五")
 8 '''
 9 Traceback (most recent call last):
10   File "D:/WorkSpace/Python_Study/test01.py", line 7, in <module>
11     test("王五")
12   File "D:/WorkSpace/Python_Study/test01.py", line 4, in test
13     assert name in ["张三","李四"],"{}不在学生列表中".format(name)
14 AssertionError: 王五不在学生列表中
15 '''

6.python中的调试方法

百度上面的方法一大堆,这里我就不多赘述了。