2.3 程序的异常处理

版权声明:@Abby-YTJ https://blog.csdn.net/weixin_43564773/article/details/85621927

1. 异常处理的基本用法

1.1 异常处理

异常

1/0

运行结果:

ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-1-9e1622b385b6> in <module>()
----> 1 1/0
ZeroDivisionError: division by zero
2 ** "abc"

运行结果:


TypeError  Traceback (most recent call last)
<ipython-input-2-99b3a2e04327> in <module>()
----> 1 2 ** "abc"
TypeError: unsupported operand type(s) for ** or pow(): 'int' and 'str'

异常处理:使程序能够应对异常情况

try:
    <语句块1>
except:
    <语句块2>

应对所有异常情况

try:
    <语句块1>
except <异常类型>:
    <语句块2>

应对特定异常情况

try:
    1/0
except:
    print("某原因异常")

运行结果:
某原因异常

try:
    1/0
except ZeroDivisionError:
    print("除数不为零")

运行结果:
除数不为零

def foo(a):
    try:
        b = 100/a
    except ZeroDivisionError:
        print("除数不为零")
        return -1
    except:
        print("未知错误")
        return -2  
foo(0)

运行结果
除数不为零
-1

foo("abc")

运行结果
未知错误
-2

2. 异常处理的高级用法

try:
    <语句块1>
except:
    <语句块2>
else:           # else:当try中<语句块1>未异常时的奖励
    <语句块3>
finally:        # finally:一定要执行的内容
    <语句块4>
try:
    print(1/a)
except:
    print("except")
else:
    print("else")
finally:
    print("finally")
a = 1

运行结果:
1.0
else
finally

try:
    print(1/a)
except:
    print("except")
else:
    print("else")
finally:
    print("finally")
a = 0
except
finally
def f(a):
    try:
        print(1/a)
        return 1/a
    except:
        print("except")
        return "except"
    else:
        print("else")
        return "else"
    finally:
        print("finally")
        return "finally"
f(1)

运行结果
1.0
finally
‘finally’

f(0)

运行结果
except
finally
‘finally’

当try-except-else-finally遇到函数

  • 无论return在哪里,finally一定执行
  • try中有return, else不执行
  • finally中的return会覆盖之前所有return

猜你喜欢

转载自blog.csdn.net/weixin_43564773/article/details/85621927
2.3