wyh551202 发表于 2022-9-29 15:58:01

2022-09-29 学习Python-Day15

异常处理,是项目施工中常见问题,要多多注意P57-P58{:10_332:}
#######################################P57
'''
捕获处理异常
'''
try:
    1/0
except:
    print('出错了1')
try:
    print(1/1)
except:
    print('出错了2')
try:
    1/0
except ZeroDivisionError:
    print('出错了3')
try:
    1/0
except ZeroDivisionError as e:
    print(e)
try:
    1/0
    520+'aa'
except(ZeroDivisionError,ValueError,TypeError):
    pass
try:
    1/0
    520+'cc'
except ZeroDivisionError:
    print('除数不能为0')
except ValueError:
    print('值不正确')
except TypeError:
    print('类型不正确')
#######################################P58
try:
    1/0
except:
    print('有异常')
else:
    print('无异常')
try:
    1/1
except:
    print('有异常')
else:
    print('无异常')
try:
    1/1
except:
    print('有异常')
else:
    print('无异常')
finally:
    print('都会执行')
try:
    f = open('./fishc.txt','w')
    f.write('I love fishc ')
except:
    print('出错了')
finally:
   f.close()
#死循环
# try:
#   while True:
#         pass
# finally:
#   print('晚安')
try:
    try:
      520+'Fishc'
    except:
      print('内部异常')
    1/0
except:
    print('外部异常')
finally:
    print('收尾')
# raiseValueError('值不正确')
# try:
#   1/0
# except:
#   raise ValueError('不行')
# raise ValueError('不行') from ZeroDivisionError
s='FishC'
assert s=='FishC'
# assert s!='FishC'
try:
    while True:
      while True:
            for i in range(10):
                if i>3:
                  raise
                print(i)
                print('跳过')
            print('跳过')
    print('跳过')
except:
    print('到这来了')

try:
    1/0
except Exception as e:
    # print(e)
    f = open('./fishc1.txt', 'a+',encoding='utf-8')
    f.write(str(e))
finally:
    f.close()

try:
    1/0
except Exception as e:
    with open('./basic_err.txt', 'a+', encoding='utf-8')as fw:
      fw.write('err:{}'.format(str(e)) + '\n')

chentyping 发表于 2022-9-30 10:19:02

真正爱学习的,赞!
页: [1]
查看完整版本: 2022-09-29 学习Python-Day15