python 6.0 error catch

6.异常处理

6.1 异常捕获

例如打开一个不存在的文件

print("before")
a = open("2.txt","r")
print("after")

报错,程序无法进行
解决:异常捕获结构来监控错误

IOError:

try:
    print("before")
    a = open("2.txt","r")
    print("after")
except IOError:#IO异常就是输入输出异常
    pass#也可以是别的函数

NameError:

try:
    print(hhh)#hhh未定义
except NameError:#IO异常就是输入输出异常
    print("错了")
  • 同时捕获加括号逗号即可(或门判断)
  • 显示错误信息 as
    try:
        print(hhh)#hhh未定义
        print("before")
        a = open("2.txt","r")
        print("after")
    except (NameError,IOError) as result:#IO异常就是输入输出异常
        print("错了")
        print(result)

捕获所有异常:Exception。Exception是所有异常的父类

6.2 try catch嵌套

import time
try:
    a =open("1213.txt","r")
    try:
        while True:#经典无条件执行
            b = a.readline()
            if len(b) == 0:
                break
            time.sleep(3)
            print(b)
    finally:  # 不论出没出错必须强制执行
        a.close()
        print("文件关闭")
except Exception:
    print("发生异常")

6.3 with as

日后填坑

暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇