异常就是程序运行时发生错误的信号(在程序出现错误时,则会产生一个异常,若程序没有处理它,则会抛出该异常,程序的运行也随之终止python
# 语法错误示范一 if # 语法错误示范二 def test: pass # 语法错误示范三 class Foo pass # 语法错误示范四 print(haha
# TypeError:int类型不可迭代 for i in 3: pass # ValueError num=input(">>: ") #输入hello int(num) # NameError aaa # IndexError l=['egon','aa'] l[3] # KeyError dic={'name':'egon'} dic['age'] # AttributeError class Foo:pass Foo.x # ZeroDivisionError:没法完成计算 res1=1/0 res2=1+'str'
在python中不一样的异常能够用不一样的类型(python中统一了类与类型,类型即类)去标识,一个异常标识一种错误。git
为了保证程序的健壮性与容错性,即在遇到错误时程序不会崩溃,咱们须要对异常进行处理安全
若是错误发生的条件是可预知的,咱们须要用if进行处理:在错误发生以前进行预防code
AGE = 18 while True: age = input('>>: ').strip() if age.isdigit(): # 只有在age为字符串形式的整数时,下列代码才不会出错,该条件是可预知的 age = int(age) if age == AGE: print('you got it') break
>>: nash
>>: sdkf
>>: 2
>>: 10
you got it
对象
若是错误发生的条件是不可预知的,则须要用到try...except:在错误发生以后进行处理索引
try:
被检测的代码块
except 异常类型:
try中一旦检测到异常,就执行这个位置的逻辑ip
列子:字符串
try: f = [ 'a', 'a', 'a', 'a', 'a', 'a', 'a', ] g = (line.strip() for line in f) print(next(g)) print(next(g)) print(next(g)) print(next(g)) print(next(g)) except StopIteration: f.close()
输出结果
a
a
a
a
a
1.异常类只能用来处理指定的异常状况,若是非指定异常则没法处理。input
s1 = 'hello' try: int(s1) except IndexError as e: # 未捕获到异常,程序直接报错 print(e)
2.多分支it
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('不管异常与否,都会执行该模块,一般是进行清理工做')
1.把错误处理和真正的工做分开来
2.代码更易组织,更清晰,复杂的工做任务更容易实现;
3.毫无疑问,更安全了,不至于因为一些小的疏忽而使程序意外崩溃了;
try: raise TypeError('抛出异常,类型错误') except Exception as e: print(e)
自定义异常
class EgonException(BaseException): def __init__(self, msg): self.msg = msg def __str__(self): return self.msg try: raise EgonException('抛出异常,类型错误') except EgonException as e: print(e)
assert 1 == 1
try: assert 1 == 2 except Exception as e: print(e)