Python's exception handling mechanism

1. What is abnormal

An exception is a signal that an error has occurred in the program, and an exception will be thrown once the program fails

Three characteristics of exception handling

Abnormal tracking information
abnormal type of
abnormality of content

Two why deal with exceptions

In order to enhance the robustness of the program, even if an error occurs during the running of the program, do not terminate the program, but catch the exception and handle it: record the error information in the log

Three how to deal with exceptions

1. Syntax errors

Processing method one: it must be corrected before the program runs

if 1>3
     print("run...")

2. Logical errors

print(x)
l=['a','b']
l[2]

1/0

int('abc')

dic={'name':'egon'}
dic['age']
class Foo:
    pass

Foo.x

3. There are two ways to deal with logical exceptions

1. The conditions under which the error occurs are predictable, use if judgment to solve

age=input('>>: ').strip() # 输入的只要不是数字就会出错
if age.isdigit():
    age=int(age)
    if age > 18:
        print('猜大了')
    elif age < 18:
        print('猜大了')
    else:
        print('猜对了')
else:
    print('必须输入数字')

2. The conditions under which the error occurs are unpredictable

print('start...')
try:
    # 有可能会抛出异常的代码
    子代码1
    子代码2
    子代码3
except 异常类型1 as e:
    pass
except 异常类型2 as e:
    pass
...
else:
    如果被检测的子代码块没有异常发生,则会执行else的子代码
finally:
    无论被检测的子代码块有无异常发生,都会执行finally的子代码

print('end...')

Usage one:

print('start...')

try:
    print('1111111111')
    l=['aaa','bbbb']
    l[3] # 抛出异常IndexError后,该行代码同级别的后续代码不会运行
    print('2222222222')
    xxx
    print('33333333')
    dic={'a':1}
    dic['a']
except IndexError as e:
    print('异常的信息: ',e)

print('end....')

#结果展示
'''
start...
1111111111
异常的信息:  list index out of range
end....
'''

Usage two:

try:
    print('1111111111')
    l=['aaa','bbbb']
    # l[3] # 抛出异常IndexError,该行代码同级别的后续代码不会运行
    print('2222222222')
    xxx
    print('33333333')
    dic={'a':1}
    dic['a']
except IndexError as e:
    print('异常的信息: ',e)
except NameError as e:
    print('异常的信息: ',e)

print('end....')

#结果展示
'''
1111111111
2222222222
异常的信息:  name 'xxx' is not defined
end....
'''

Usage three:

try:
    print('1111111111')
    l=['aaa','bbbb']
    # l[3] # 抛出异常IndexError,该行代码同级别的后续代码不会运行
    print('2222222222')
    xxx
    print('33333333')
    dic={'a':1}
    dic['a']
# except IndexError as e: #异常信息
#     print('异常的信息: ',e)
# except NameError as e:
#     print('异常的信息: ',e)
except Exception as e:
    print('所有异常都可以匹配到')

print('end....')

#结果展示
'''
1111111111
2222222222
所有异常都可以匹配到
end....
'''

Usage four: else cannot be used alone with try, it must be used with except

print('start...')

try:
    print('1111111111')
    print('2222222222')
    # xxxx
    print('33333333')
except Exception as e:  # 万能异常
    print('所有异常都可以匹配的到')
else:  #当不发生异常时执行
    print('====>')

print('end....')

Usage five: finally can be used alone with try

Finally: It does not handle exceptions, no matter whether an exception occurs, it will execute finally subcode

The code for reclaiming system resources is generally placed here, so that regardless of whether the program encounters an error and stops, it can recycle system resources.

print('start...')

try:
    print('1111111111')
    l = ['aaa', 'bbbb']
    l[3] # 抛出异常IndexError,该行代码同级别的后续代码不会运行
    print('2222222222')
    xxx
    print('33333333')
    dic = {'a': 1}
    dic['aaa']
finally: # 不处理异常,无论是否发生异常都会执行finally的子代码
    print('====》》》》》应该把被检测代码中回收系统资源的代码放到这里')

print('end....')

Guess you like

Origin www.cnblogs.com/xy-han/p/12716035.html