033 异常处理

异常处理

异常就是程序运行时发生错误的信号(在程序出现错误时,则会产生一个异常,若程序没有处理它,则会抛出该异常,程序的运行也随之终止

在python中不同的异常可以用不同的类型(python中统一了类与类型,类型即类)去标识,一个异常标识一种错误

1.语法异常

2.逻辑异常

3.异常处理

为了保证程序的健壮性与容错性,即在遇到错误时程序不会崩溃,我们需要对异常进行处理

1.提前预防

如果错误发生的条件是可预知的,我们需要用if进行处理:在错误发生之前进行预防

2.之后预防

如果错误发生的条件是不可预知的,则需要用到try...except:在错误发生之后进行处理

#基本语法为
try:
    被检测的代码块
except 异常类型:
    try中一旦检测到异常,就执行这个位置的逻辑

1.异常类只能用来处理指定的异常情况,如果非指定异常则无法处理。

s1 = 'hello'
try:
    int(s1)
except IndexError as e:  # 未捕获到异常,程序直接报错
    print(e)

2.多分支

s1 = 'hello'
try:
    int(s1)
except IndexError as e:
    print(e)
except KeyError as e:
    print(e)
except ValueError as e:
    print(e)
invalid literal for int() with base 10: 'hello'

3.万能异常Exception

s1 = 'hello'
try:
    int(s1)
except Exception as e:
    print(e)

4.多分支异常与万能异常

  • 如果你想要程序无论出现什么异常,我们统一丢弃,或者使用同一段代码逻辑去处理他们那么只有一个Exception就足够了。
  • 如果想要对于不同的异常我们需要定制不同的处理逻辑,那就需要用到多分支了。

5.也可以在多分支后来一个Exception

s1 = 'hello'
try:
    int(s1)
except IndexError as e:
    print(e)
except KeyError as e:
    print(e)
except ValueError as e:
    print(e)
except Exception as e:
    print(e)

6.异常的最终执行

s1 = 'hello'
try:
    int(s1)
except IndexError as e:
    print(e)
except KeyError as e:
    print(e)
except ValueError as e:
    print(e)
#except Exception as e:
#    print(e)
else:
    print('try内代码块没有异常则执行我')
finally:
    print('无论异常与否,都会执行该模块,通常是进行清理工作')

4.抛出异常(raise)

try:
    raise TypeError('抛出异常,类型错误')
except Exception as e:
    print(e)

5.断言(assert)

assert 1 == 1

try:
    assert 1 == 2
except Exception as e:
    print(e)

猜你喜欢

转载自www.cnblogs.com/xichenHome/p/11311459.html
今日推荐