异常处理

# def func():name
# def main():
#     func()
# main()
# 排错信息从后往前看
'''
Traceback (most recent call last):
  File "/Users/jerry/code/test/selenium/oldboy/day24(new,del,item/day24.py", line 118, in <module>
    main()
  File "/Users/jerry/code/test/selenium/oldboy/day24(new,del,item/day24.py", line 117, in main
    func()
  File "/Users/jerry/code/test/selenium/oldboy/day24(new,del,item/day24.py", line 115, in func
    def func():name
NameError: name 'name' is not defined
'''


a = [1, 2, 3, 4]
try:
    num = int(input('num: '))
    print(a[num])
except ValueError:
    print('请输入数字')
except IndexError:
    print('输入超范围')
except Exception as e: # 所有异常捕获,但是无法区分是什么异常,可使用as 将异常输出
    print('其他错误', e)
else:
    print('执行成功')
finally:
    print('finally always run')
'''
try中的代码:
    一旦发生异常,后面代码就不执行,会直接跳到except的位置
    一个错误类型只能处理一种错误
    出现异常后,会从上到下去匹配except的ERROR,匹配到错误类型后不再执行其他except
    所以有多个except时,Exception一定要放在最后,否则Exception 之后的异常不被执行
    else的代码在try执行后不抛异常时执行,如果有except则else不执行
    finally 无论是否异常均会执行,用来归还系统资源,使用场景:try 执行打开文件操作,如执行异常,finally可保证文件被close
    格式:    try except
                try except else
                try except else finally
                try finally

# finally 其他使用场景,try正常执行,但在return之前扔回执行finally将文件关闭
def test():
    try:
        f = open('1.log', 'w')
        content = f.read()
        return content
    finally:
        f.close()

 

# 主动异常
# raise TypeError('主动异常')

# 断言异常,true时正常执行,false时抛异常
# assert 1 == 2 # AssertionError

# 自定义异常
class EX(BaseException): # 所有异常都继承BaseException类
    def __init__(self, msg):
        self.msg = msg

try:
    raise EX('自定义异常')
except EX as e:
    print(e)  # 自定义异常

 

posted @ 2025-02-19 21:03  尐少  阅读(8)  评论(0)    收藏  举报