Python3-2020-测试开发-22- 异常

Python 程序的语法是正确的,在运行它的时候,也有可能发生错误。运行期检测到的错误被称为异常。

一、异常处理

1. try...except....

"""1. try...except...."""

try:
    a = 3/0
except BaseException as e:

    print(e)
    print(type(e))



——————————————————————————————
division by zero
<class 'ZeroDivisionError'>

2. try...except...except...except...

"""2. try...except...except...except..."""
# 一个 try 语句可能包含多个except子句,分别来处理不同的特定的异常。最多只有一个分支会被执行 

3. try...except....else   

如果有异常执行except,没有异常执行else
"""3. try...except....else"""
# 如果有异常执行except,没有异常执行else
try:

    a = 3/2

except BaseException as e:

    print(e)

else:

    print("无异常!")   # 无异常!


___________________________________________
无异常!

4. try...except...else...finally...

finally块无论是否发生异常都会被执行,通常用来释放try块中的申请资源
"""4. try...except...else...finally..."""
# finally块无论是否发生异常都会被执行,通常用来释放try块中的申请资源

try:

    f = open("/Users/chushujin/chushujin/myworkspsace/csjin-Test/mypythonscript","r")
    content = f.readline()
    print(content)
except IOError as e:

    print(e)
finally:
    pass

5. return语句一般不放在try...except...else...finally块中,建议放到最后

"""5. return语句一般不放在try...except...else...finally块中,建议放到最后"""
def test001():

    try:
        print("1")
    except Exception as e:
        print(e)
    finally:
        print("结束")

    return "1"

 

二、常见的异常

1. 语法错误:invalid syntax

# 6.1 语法错误:invalid syntax

  int a =3



——————————————————————————————————
  File "C:/chushujin/study/mypythonscript/src/com.csjin.qa2020/TestException/Test01.py", line 61
    int a =3
    ^
IndentationError: unexpected indent

2. 尝试访问一个没有申明的变量:NameError: name 'b' is not defined

# 6.2 尝试访问一个没有申明的变量:NameError: name 'b' is not defined

 print(b)

——————————————————————————————

Traceback (most recent call last):
  File "C:/chushujin/study/mypythonscript/src/com.csjin.qa2020/TestException/Test01.py", line 66, in <module>
    print(b)
NameError: name 'b' is not defined

3. 除数不能为0:ZeroDivisionError: division by zero

#6.3 除数不能为0:ZeroDivisionError: division by zero

# a = 3/0

———————————————————————————————————
Traceback (most recent call last):
  File "C:/chushujin/study/mypythonscript/src/com.csjin.qa2020/TestException/Test01.py", line 70, in <module>
    a = 3/0
ZeroDivisionError: division by zero

4. 数值错误:ValueError: could not convert string to float: '褚'

# 6.4 数值错误:ValueError: could not convert string to float: '褚'
# float("褚")

————————————————————————————————
Traceback (most recent call last):
  File "C:/chushujin/study/mypythonscript/src/com.csjin.qa2020/TestException/Test01.py", line 73, in <module>
    float("")
ValueError: could not convert string to float: ''

5. 类型错误:TypeError: unsupported operand type(s) for +: 'int' and 'str'

# 6.5 类型错误:TypeError: unsupported operand type(s) for +: 'int' and 'str'
 123+"abc"


——————————————————————————————————
Traceback (most recent call last):
  File "C:/chushujin/study/mypythonscript/src/com.csjin.qa2020/TestException/Test01.py", line 76, in <module>
    123+"abc"
TypeError: unsupported operand type(s) for +: 'int' and 'str'

6. 访问对象的不存在的属性:AttributeError: 'str' object has no attribute 'say'

# 6.6 访问对象的不存在的属性:AttributeError: 'str' object has no attribute 'say'
a = "666"
 a.say()

——————————————————————————————————


Traceback (most recent call last):
  File "C:/chushujin/study/mypythonscript/src/com.csjin.qa2020/TestException/Test01.py", line 80, in <module>
    a.say()
AttributeError: 'str' object has no attribute 'say'

7. 索引越界异常:IndexError: string index out of range

# 6.7 索引越界异常:IndexError: string index out of range
b = [1,2,3]
 a[10]

——————————————————————————————————
Traceback (most recent call last):
  File "C:/chushujin/study/mypythonscript/src/com.csjin.qa2020/TestException/Test01.py", line 84, in <module>
    a[10]
IndexError: string index out of range

8. 字段关键字不存在:KeyError: 'n'

# 6.8 字段关键字不存在:KeyError: 'n'
d = {"name":"chu"}
d['n']

——————————————————————————————————
Traceback (most recent call last):
  File "C:/chushujin/study/mypythonscript/src/com.csjin.qa2020/TestException/Test01.py", line 88, in <module>
    d['n']
KeyError: 'n'

 

三、使用with  content_expr [as f]:自动关闭。无需手动关闭文件

import os


path = os.path.split(os.path.split(os.path.realpath(__file__))[0])[0]
# ('C:\\chushujin\\study\\mypythonscript\\src\\com.csjin.qa2020\\TestException', 'Test02.py')
print(path)

path_txt = os.path.join(path,"test.txt")

""" with context_expr [as f]"""

with open(path_txt,encoding="utf-8") as f:

    print(f.readline())

 

四、traceback模块使用

1. 打印详细信息

"""traceback使用"""
import os

path = os.path.split(os.path.split(os.path.realpath(__file__))[0])[0]
# ('C:\\chushujin\\study\\mypythonscript\\src\\com.csjin.qa2020\\TestException', 'Test02.py')
print(path)

path_txt = os.path.join(path,"test.txt")

import traceback

try:

    a = 3/0

except:

    traceback.print_exc()

——————————————————————————————————

"""
Traceback (most recent call last):
  File "C:/chushujin/study/mypythonscript/src/com.csjin.qa2020/TestException/Test03.py", line 9, in <module>
    a = 3/0
ZeroDivisionError: division by zero
"""

2. 将异常写入文件

try:

    a = 3/0

except:

    # 将错误信息输入至文件
    with open(path_txt,"a") as f:

        traceback.print_exc(file=f)

文件中展示为:

111111111111111111Traceback (most recent call last):
  File "C:/chushujin/study/mypythonscript/src/com.csjin.qa2020/TestException/Test03.py", line 32, in <module>
    a = 3/0
ZeroDivisionError: division by zero
Traceback (most recent call last):
  File "C:/chushujin/study/mypythonscript/src/com.csjin.qa2020/TestException/Test03.py", line 32, in <module>
    a = 3/0
ZeroDivisionError: division by zero

 

五、自定义异常

Python 使用 raise 语句抛出一个指定的异常。

raise 唯一的一个参数指定了要被抛出的异常。它必须是一个异常的实例或者是异常的类(也就是 Exception 的子类)。

只想知道这是否抛出了一个异常,并不想去处理它,那么一个简单的 raise 语句就可以再次把它抛出。

 

"""自定义异常"""


class AgeError(Exception):

    def __init__(self,errorInfo):

        Exception.__init__(self)
        self.errorInfo = errorInfo


    def __str__(self):

        return str(self.errorInfo)+"年龄错误"



############################################
if __name__ == '__main__':

    age = int(input("请输入一个数字:"))

    if age < 1 or age >150:

        raise AgeError(age)

    else:

        print("年龄正常")


"""
__main__.AgeError: 200年龄错误
"""

 

posted @ 2020-06-23 16:07  旅行没有终点  阅读(165)  评论(0编辑  收藏  举报