Python basic study notes 09-abnormal

1. Abnormal

Syntax:
try:
code that may cause errors
except: code
that is executed if an exception occurs

1.1 Catch the exception
Note:
If the exception type of the code you are trying to execute is inconsistent with the exception type to be caught, you cannot catch the exception.
Generally, only one line of code to be executed is placed under try

1.2 Catch the specified exception
Syntax:
try:
code that may cause an error
except exception type:
code to be executed if an exception occurs

1.3 Capture multiple specified exceptions, capture exception description information, and capture all exceptions.
When capturing multiple exceptions, you can put the name of the exception type to be captured after except, and write it in a tuple

try:
    print(1/0)
except(NameError,ZeroDivisionError) as result:
    print(result)		# division by zero

Catch all exceptions:

try:
    print(num)
except Exception as result:
    print(result)		# name 'num' is not defined

1.4 The abnormal else
else means that if there is no abnormal execution code

num = 0
try:
    print(num)
except Exception as result:
    print(result)
else:
    print("无异常")

1.5 The finally finally of the
exception indicates the code to be executed regardless of whether the exception is

num = 0
try:
    print(num)		# 可能发生异常
except Exception as result:
    print(result)	# 如果出现异常
else:
    print("无异常")	# 无异常
finally:			
    print("continue")	# 无论异常都执行

1.6 Custom exception

# 自定义异常类
class ShortInputError(Exception):
    def __init__(self,length,min_len):
        self.length = length
        self.min_len = min_len
    # 设置异常描述信息
    def __str__(self):
        return f'你输入的长度是{self.length},不能少于{self.min_len}'

def main():
    try:
        con = input("请输入密码")
        if len(con) < 3:	# 异常产生条件
            raise ShortInputError(len(con),3)       # 抛出异常
    except Exception as result:     # 捕获异常
        print(result)
    else:
        print("密码输入完成")

Guess you like

Origin blog.csdn.net/qq_44708714/article/details/105052271