14 python 错误和异常

学习python之处一定会遇到一些报错,一般出错后会有提示信息,如果能看懂基本的英文单词,基本上都能够发现错误所在。

python中有两种错误容易辨认:语法错误和异常。
错误
首先,语法错误又称之为解析错误,比如,当少写了引号、括号,或者某个关键字写错了都会提示出语法错误。

>>> print "ss"
    SyntaxError: Missing parentheses in call to 'print'. Did you mean print("ss")?
>>> 

一般会给出错误的位置,如果是简单的语法错误还是比较容易纠正的。上面的python3例子中,输出print语句的语法错误,没有加括号。

异常:
异常就是当你的程序语法是完全正确的,但是在运行的时候还是可能会发生错误,运行监测到的错误被称为异常,大多数的异常不会被程序处理,都以错误信息的形式展现在这里。

while True:
x = int(input())
for i  in range(1,x):
    if x%i == 0:
        print(i)

输出:

ValueError: invalid literal for int() with base 10: 's'

python常见异常类型:
1、NameError:尝试王文一个未申请的变量

>>>s
NameError: name 's' is not defined

2、ZeroDivisionError:除数为0

>>> v = 10
>>> v/0
Traceback (most recent call last):
      File "<pyshell#2>", line 1, in <module>
v/0
ZeroDivisionError: division by zero

3、SyntaxError:语法错误

>>> print "s"
SyntaxError: Missing parentheses in call to 'print'. Did you mean print("s")?
>>> 

4、IndexError:索引超出范围

>>> list =[1,2,3]
>>> list[4]
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
list[4]
IndexError: list index out of range
>>> 

5、KeyError:字典关键字不存在

>>> dict1 = {'name':'Tom','Age':20}
>>> dict1['gender']
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
dict1['gender']
KeyError: 'gender'
>>> 

6、FileNotFoundError:找不到指定文件错误

>>> f = open('123.txt')
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
f = open('123.txt')
FileNotFoundError: [Errno 2] No such file or directory: '123.txt'
>>> 

7、AttributeError:访问未知对象属性

>>> import math
>>> math.p
Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
math.p
AttributeError: module 'math' has no attribute 'p'

8、ValueError:数值错误

>>> int('d')
Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
int('d')
ValueError: invalid literal for int() with base 10: 'd'
>>> 

9、TypeError:类型错误

>>> str1 = 'abcd'
>>> a =20
>>> str1+a
Traceback (most recent call last):
  File "<pyshell#14>", line 1, in <module>
str1+a
TypeError: must be str, not int
>>> 

10、断言错误:

>>> a =1
>>> assert a!=1
Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
assert a!=1
AssertionError
>>> 

11、NotImplementedError:方法没实现引起的异常
12、MemoryError:内存耗尽异常
13、LookupError:键、值不存在引发的异常

LookupError异常是IndexError、KeyError的基类, 如果你不确定数据类型是字典还是列表时,可以用LookupError捕获此异常

14、StandardError 标准异常

除StopIteration, GeneratorExit, KeyboardInterrupt 和SystemExit外,其他异常都是StandarError的子类。
错误检测与异常处理区别在于:错误检测是在正常的程序流中,处理不可预见问题的代码,例如一个调用操作未能成功结束。

异常处理:
通常情况下使用如下语句处理异常:

try:
   语句
 except 错误类型:
     语句(出现相应错误类型时执行,否则不执行)
 else:
     语句
 finally:
      语句

如果一个异常在 try 子句里(或者在 except 和 else 子句里)被抛出,而又没有任何的 except 把它截住,那么这个异常会在 finally 子句执行后再次被抛出。

例如:让用户输入一个整数,如果用户输入的不是数字类型,那么允许中断这个程序。

while True:
    try:
          x = int(input())
            for i  in range(1,x):
                if x%i == 0:
                    print(i)
    except ValueError:
        print("请输入数字,再试一次")

try语句按照如下方式工作;

首先,执行try子句(在关键字try和关键字except之间的语句)
如果没有异常发生,忽略except子句,try子句执行后结束。
如果在执行try子句的过程中发生了异常,那么try子句余下的部分将被忽略。如果异常的类型和 except 之后的名称相符,那么对应的except子句将被执行。最后执行 try 语句之后的代码。
如果一个异常没有与任何的except匹配,那么这个异常将会传递给上层的try中

一个 try 语句可能包含多个except子句,分别来处理不同的特定的异常。最多只有一个分支会被执行。
处理程序将只针对对应的try子句中的异常进行处理,而不是其他的 try 的处理程序中的异常。
最后一个except子句可以忽略异常的名称,它将被当作通配符使用。你可以使用这种方法打印一个错误信息,然后再次把异常抛出。

import sys

try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except OSError as err:
    print("OS error: {0}".format(err))
except ValueError:
    print("Could not convert data to an integer.")
except:
    print("Unexpected error:", sys.exc_info()[0])
    raise

例如:

>> def f(x,y):
try:
    s=x/y
except ZeroDivisionError:
    print("除数不能为0")
else:
    print("结果为:",s)
finally:
    print("执行finally clause")   
>>> f(1,1)
结果为: 1.0
执行finally clause
>>> f(3,0)
除数不能为0
执行finally clause
>>> f('1','2')
执行finally clause
Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
f('1','2')
  File "<pyshell#9>", line 3, in f
s=x/y
TypeError: unsupported operand type(s) for /: 'str' and 'str'
>>> 

猜你喜欢

转载自blog.csdn.net/qq_42397914/article/details/81609232