目录python
异常就是程序运行时发生错误的信号(在程序出现错误时,则会产生一个异常,若程序没有处理它,则会抛出该异常,程序的运行也随之终止)。git
语法错误,根本过不了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中统一了类与类型,类型即类)去标识,==一个异常标识一种错误==。框架
为了保证程序的健壮性与容错性,即在遇到错误时程序不会崩溃,咱们须要对异常进行处理,目的就是为了程序可以正常运行。调试
Age = 10 while True: age = input('>>:').strip() if age.isdigit(): age = int(age) if age == Age: print('you got it') break #输出: >>:chen >>:2 >>:10 you got it
若是错误发生的条件是不可预知的,则须要用到try...except:在错误发生以后进行处理code
#基本语法 try: 被检测的代码 except 异常类型: try中一旦检测的异常,就会执行这个位置的逻辑
举例对象
try: f = [ '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
异常类只能用来处理指定的异常状况,若是非指定异常则没法处理blog
s1 = 'hello' try: int(s1) except IndexError as e: # 未捕获到异常,程序直接报错,异常不一样 print(e)
多分支索引
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'
万能异常Exceptionip
s1 = 'hello' try: int(s1) except Exception as e: print(e) #输出: invalid literal for int() with base 10: 'hello'
多分支异常和万能异常
万能异常:不管出现什么异常,咱们统一丢弃,或者说使用同一段代码逻辑去处理他们。
多分支异常:对于不一样的异常咱们须要定制不一样的处理逻辑,那就须要用到多分支了。
在多分支后来一个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) #输出: invalid literal for int() with base 10: 'hello' ## 多分支异常处理检测出异常后,万能异常就不会起做用了
异常的最终执行
最终的意思,不管报不报错都会打印
s1 = 'hello' try: int(s1) except IndexError as e: print(e) except KeyError as e: print(e) except ValueError as e: print(e) else: print('try内代码块没有异常则执行我') finally: print('不管异常与否,都会执行该模块,一般是进行清理工做') #输出: invalid literal for int() with base 10: 'hello' 不管异常与否,都会执行该模块,一般是进行清理工做
try: raise TypeError('抛出异常,类型错误') except Exception as e: print(e) #输出: 抛出异常,类型错误
raise 主动抛错,没有用.
做用: 建立框架/建立语言 C/C++ 有用
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) #输出: 抛出异常,类型错误
断言,最先的时候没有pycharm,用这个作调试。
assert 1==1
条件成立会跳过,条件错误会报AssertionError错误
try: assert 1 == 2 except Exception as e: print(e)