错误和异常
错误:
# 错误分为两种: 1.语法错误,没有按照python语言的规则去写,导致的错误
# 2. 逻辑错误
# 语法错误1,比如: print("dlkafkld" # 少一个括号 # 语法错误2,比如: a = 1 if a=1 # 少个: print("daff") # 语法错误3,比如: def a: pass
# 逻辑错误1 num = int(input(">>>")) print(num) # 执行结果: >>>fadsfa Traceback (most recent call last): File "E:/seafile backup/python3/python3 project/day 29/s1 错误和异常.py", line 18, in <module> num = int(input(">>>")) ValueError: invalid literal for int() with base 10: 'fadsfa' # 逻辑错误2 print(aaa) # 执行结果 Traceback (most recent call last): File "E:/seafile backup/python3/python3 project/day 29/s1 错误和异常.py", line 33, in <module> print(aaa) NameError: name 'aaa' is not defined # 逻辑错误3 l = ["2","daf"] print(l[100]) # 执行结果 Traceback (most recent call last): File "E:/seafile backup/python3/python3 project/day 29/s1 错误和异常.py", line 44, in <module> print(l[100]) IndexError: list index out of range # 逻辑错误4 dic = {'name':'alex'} print(dic["xiao"]) 执行结果: Traceback (most recent call last): File "E:/seafile backup/python3/python3 project/day 29/s1 错误和异常.py", line 57, in <module> print(dic["xiao"]) KeyError: 'xiao' # 逻辑错误5 class Foo: pass print(Foo.name) 执行结果: Traceback (most recent call last): File "E:/seafile backup/python3/python3 project/day 29/s1 错误和异常.py", line 66, in <module> print(Foo.name) AttributeError: type object 'Foo' has no attribute 'name' # 逻辑错误6 a = 1/0 print(a) 执行结果: Traceback (most recent call last): File "E:/seafile backup/python3/python3 project/day 29/s1 错误和异常.py", line 74, in <module> a = 1/0 ZeroDivisionError: division by zero '''
# 异常:
异常就是程序运行时发生错误的信号(在程序出现错误时,则会产生一个异常,若程序没有处理它,则会抛出该异常,程序的运行也随之终止)
a = 1/0 print(a) 执行结果: Traceback (most recent call last): # Traceback :异常的追踪信息 File "E:/seafile backup/python3/python3 project/day 29/s1 错误和异常.py", line 74, in <module> a = 1/0 # 引发异常的错误 ZeroDivisionError: division by zero # ZerDivisionError:异常类 division by zero 异常值 # 异常的种类: AttributeError 试图访问一个对象没有的树形,比如foo.x,但是foo没有属性x IOError 输入/输出异常;基本上是无法打开文件 ImportError 无法引入模块或包;基本上是路径问题或名称错误 IndentationError 语法错误(的子类) ;代码没有正确对齐 IndexError 下标索引超出序列边界,比如当x只有三个元素,却试图访问x[5] KeyError 试图访问字典里不存在的键 KeyboardInterrupt Ctrl+C被按下 NameError 使用一个还未被赋予对象的变量 SyntaxError Python代码非法,代码不能编译(个人认为这是语法错误,写错了) TypeError 传入对象类型与要求的不符合 UnboundLocalError 试图访问一个还未被设置的局部变量,基本上是由于另有一个同名的全局变量, 导致你以为正在访问它 ValueError 传入一个调用者不期望的值,即使值的类型是正确的 常用异常: ArithmeticError AssertionError AttributeError BaseException BufferError BytesWarning DeprecationWarning EnvironmentError EOFError Exception FloatingPointError FutureWarning GeneratorExit ImportError ImportWarning IndentationError IndexError IOError KeyboardInterrupt KeyError LookupError MemoryError NameError NotImplementedError OSError OverflowError PendingDeprecationWarning ReferenceError RuntimeError RuntimeWarning StandardError StopIteration SyntaxError SyntaxWarning SystemError SystemExit TabError TypeError UnboundLocalError UnicodeDecodeError UnicodeEncodeError UnicodeError UnicodeTranslateError UnicodeWarning UserWarning ValueError Warning ZeroDivisionError
异常的处理方式:
# 异常处理1: 用if来处理异常 a = (input(">>>")) if a.isdigit(): a = int(a) else: print("%s不是数字"%a) print(a) # 处理结果1: >>>gsf gsf不是数字 gsf # 处理结果2: >>>45 45 # 异常处理2:用try 和 except来处理异常 ====》万能异常 a = (input(">>>")) try: a = int(a) except Exception: print("输入的有误") print(a) # 处理结果1: >>>gadsf 输入的有误 gadsf # 处理结果2: >>>45 45 # 异常处理3: ====》针对某种异常进行处理 try: print(a) # 出现找不到变量名时会触发NameError except NameError: print("__NameError__") # 异常处理4: ====》多分支异常 try: print(a) l = ["a","b"] print(l[100]) except NameError as e: print(e) except ValueError as e: print(e) except Exception: print("万能异常")
# 总结try..except
# 1:把错误处理和真正的工作分开来 # 2:代码更易组织,更清晰,复杂的工作任务更容易实现; # 3:毫无疑问,更安全了,不至于由于一些小的疏忽而使程序意外崩溃了;
什么时候用异常处理?
首先try...except是你附加给你的程序的一种异常处理的逻辑,与你的主要的工作是没有关系的,这种东西加的多了,会导致你的代码可读性变差 然后异常处理本就不是你2b逻辑的擦屁股纸,只有在错误发生的条件无法预知的情况下,才应该加上try...except
end
对于一个有思想的人来说,没有地方是荒凉而遥远的