21.python异常处理和断言

python异常处理和断言

异常捕获流程

捕捉异常可以使用try/except语句。

try/except语句用来检测try语句块中的错误,从而让except语句捕获异常信息并处理。

try:
	<语句>        # 运行别的代码
except <名字>:
	<语句>        # 如果在try部份引发了'name'异常
except <名字>,<数据>:
	<语句>        # 如果引发了'name'异常,获得附加的数据
else:
	<语句>        # 如果没有异常发生
finally:
	<语句>    	# 无论是否发生异常,退出try时总会执行

案例

#!/usr/bin/python
# -*- coding: UTF-8 -*-

try:
    fh = open("testfile", "w")
    fh.write("这是一个测试文件,用于测试异常!!")
except IOError:
    print ("Error: 没有找到文件或读取文件失败")
else:
    print "内容写入文件成功"
    fh.close()

触发异常

使用raise语句自己触发异常

1.创建一个Exception的对象

2.使用raise关键字抛出异常对象(语法:raise 异常对象)

def functionName( level ):
    if level < 1:
        raise Exception("Invalid level!", level)
        # 触发异常后,后面的代码就不会再执行
def input_password():

    # 1.提示用户输入密码
    pwd = input("请输入密码:")

    # 2. 判断密码长度 >=8 ,返回用户输入的密码
    if len(pwd) >= 8:
        return pwd

    # 3. 如果<8,主动抛出异常
    print("主动抛出异常")
    # > 1.创建一个Exception的对象,可以使用错误信息字符串作为参数
    ex = Exception("密码长度不够")

    # > 2.使用raise关键字抛出异常对象
    raise ex


# 提示用户输入密码
try:
    print(input_password())
except Exception as result:
    print(result)
def AbyB(a , b):
    try:
        c = ((a+b) / (a-b))
    except ZeroDivisionError:
        print ("a/b result in 0")
    else:
        print (c)

# Driver program to test above function
AbyB(2.0, 3.0)
AbyB(3.0, 3.0)

# 输出结果
-5.0
a/b result in 0 

异常类型

 1 BaseException
 2  +-- SystemExit
 3  +-- KeyboardInterrupt
 4  +-- GeneratorExit
 5  +-- Exception
 6       +-- StopIteration
 7       +-- StopAsyncIteration
 8       +-- ArithmeticError
 9       |    +-- FloatingPointError
10       |    +-- OverflowError
11       |    +-- ZeroDivisionError
12       +-- AssertionError
13       +-- AttributeError
14       +-- BufferError
15       +-- EOFError
16       +-- ImportError
17            +-- ModuleNotFoundError
18       +-- LookupError
19       |    +-- IndexError
20       |    +-- KeyError
21       +-- MemoryError
22       +-- NameError
23       |    +-- UnboundLocalError
24       +-- OSError
25       |    +-- BlockingIOError
26       |    +-- ChildProcessError
27       |    +-- ConnectionError
28       |    |    +-- BrokenPipeError
29       |    |    +-- ConnectionAbortedError
30       |    |    +-- ConnectionRefusedError
31       |    |    +-- ConnectionResetError
32       |    +-- FileExistsError
33       |    +-- FileNotFoundError
34       |    +-- InterruptedError
35       |    +-- IsADirectoryError
36       |    +-- NotADirectoryError
37       |    +-- PermissionError
38       |    +-- ProcessLookupError
39       |    +-- TimeoutError
40       +-- ReferenceError
41       +-- RuntimeError
42       |    +-- NotImplementedError
43       |    +-- RecursionError
44       +-- SyntaxError
45       |    +-- IndentationError
46       |         +-- TabError
47       +-- SystemError
48       +-- TypeError
49       +-- ValueError
50       |    +-- UnicodeError
51       |         +-- UnicodeDecodeError
52       |         +-- UnicodeEncodeError
53       |         +-- UnicodeTranslateError
54       +-- Warning
55            +-- DeprecationWarning
56            +-- PendingDeprecationWarning
57            +-- RuntimeWarning
58            +-- SyntaxWarning
59            +-- UserWarning
60            +-- FutureWarning
61            +-- ImportWarning
62            +-- UnicodeWarning
63            +-- BytesWarning
64            +-- ResourceWarning

常见的异常类型如下:
Exception:所有异常的基类,因为所有python异常类都是基类Exception的其中一员,异常都是从基类Exception继承的,并且都在exceptions python 模块中定义。

AttributeError:   属性错误,特性引用和赋值失败时会引发属性错误
NameError:        试图访问的变量名不存在
SyntaxError:      语法错误,代码形式错误
IOError:          python ioerror,一般常见于打开不存在文件时会引发IOError错误,也可以解理为输出输入错误
KeyError:         使用了映射中不存在的关键字(键)时引发的关键字错误
IndexError:       索引错误,使用的索引不存在,常索引超出序列范围
TypeError:        类型错误,内建操作或是函数应于在了错误类型的对象时会引发类型错误
ZeroDivisonError: 除数为0,在用除法操作时,第二个参数为0时引发了该错误
ValueError:       值错误,传给对象的参数类型不正确,像是给int()函数传入了字符串数据类型的参数。

异常处理的优点

  • 提高程序可靠性:通过正确处理异常,可以防止程序由于意外错误或输入而崩溃或产生不正确的结果。
  • 简化错误处理:异常处理允许您将错误处理代码与主程序逻辑分离,从而更易于阅读和维护代码。
  • 更干净的代码:通过异常处理,您可以避免使用复杂的条件语句来检查错误,从而使代码更清晰,可读性更强。
  • 更容易调试:当一个异常被抛出时,Python解释器会打印一个回溯,显示异常发生的确切位置,从而更容易调试代码。

断言函数assert

Python assert(断言)用于判断一个表达式,在表达式条件为 false 的时候触发异常。

断言可以在条件不满足程序运行的情况下直接返回错误,而不必等待程序运行后出现崩溃的情况

assert 断言成功则继续进行,断言失败则程序报错

1.断言能够别人更好的理解自己的代码

2.找出程序中逻辑不对的一方面

3.断言会提示某个对象会处于何种状态

语法:assert expression1 [, expression2]
assert <断言判断条件> [,"错误提示消息"]
assert condition

 if not condition:
  raise AssertionError()
import sys
assert ('linux' in sys.platform), "该代码只能在 Linux 下执行"

# 执行结果
AssertionError: 该代码只能在 Linux 下执行


def is_even(num):
    return num % 2 == 0

# 判断一个数是否为偶数
assert is_even(10), "这不是一个偶数"
posted @ 2023-10-19 09:28  贝壳里的星海  阅读(40)  评论(0编辑  收藏  举报