Python—异常处理

对于我们写程序的人来说,出现错误是避免不了,如果我们在写程序的过程中出现了错误,我建议每一位写程序的人,先从自己身上找错误,不要总是觉得自己是对的,这样很不好,不利于我们找到错误,也不利于我们的成长。

下面举一个列子 :

我们写一个读取文件内容的程序:

file_name= input('请输入一个文件名:')
f = open(file_name)
print('文件的内容是:')
for each_line in f:
      print(each_line)
      

运行之后我们输入一个文件名(不加后缀)之后python就会给出异常的 类型:

请输入一个文件名:test
Traceback (most recent call last):
  File "D:\Python\test\test.py", line 2, in <module>
    f = open(file_name)
FileNotFoundError: [Errno 2] No such file or directory: 'test'
>>> 

Python提醒我们这个文件不存在,如果我们加上后缀名,就可以顺利的打开。

下面列举一下常见的异常:

AssertionError断言语句(assert)失败
AttributeError尝试访问未知的对象属性
EOFError用户输入文件末尾标志EOF(Ctrl+d
FloatingPointError浮点计算错误
GeneratorExitgenerator.close()方法被调用的时候
ImportError导入模块失败的时候
IndexError索引超出序列的范围
KeyError字典中查找一个不存在的关键字
KeyboardInterrupt用户输入中断键(Ctrl+c)
MemoryError内存溢出(可通过删除对象释放内存)
NameError尝试访问一个不存在的变量
NotImplementedError尚未实现的方法
OSError操作系统产生的异常(例如打开一个不存在的文件)
OverflowError数值运算超出最大限制
ReferenceError弱引用(weak reference)试图访问一个已经被垃圾回收机制回收了的对象
RuntimeError一般的运行时错误
StopIteration迭代器没有更多的值
SyntaxErrorPython的语法错误
IndentationError缩进错误
TabErrorTab和空格混合使用
SystemErrorPython编译器系统错误
SystemExitPython编译器进程被关闭
TypeError不同类型间的无效操作
UnboundLocalError访问一个未初始化的本地变量(NameError的子类)
UnicodeErrorUnicode相关的错误(ValueError的子类)
UnicodeEncodeErrorUnicode编码时的错误(UnicodeError的子类)
UnicodeDecodeErrorUnicode解码时的错误(UnicodeError的子类)
UnicodeTranslateErrorUnicode转换时的错误(UnicodeError的子类)
ValueError传入无效的参数
ZeroDivisionError除数为零

列举出来并不是为了记住,而是碰到的时候可以查看

针对上面的一些异常举例:

>>> list1 = ['xiaoyi']
>>> assert  len(list1) > 0
>>> list1.pop()
'xiaoyi'
>>> assert  len(list1) > 0
Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    assert  len(list1) > 0
AssertionError
>>> list2 = [1,2,3]
>>> list2[3]
Traceback (most recent call last):
  File "<pyshell#15>", line 1, in <module>
    list2[3]
IndexError: list index out of range
>>> dict1 = {'one':1,'two':2}
>>> dict1['three']
Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    dict1['three']
KeyError: 'three'
>>> dict1.get('three')
>>> dict1.get('one')
1
>>> abc
Traceback (most recent call last):
  File "<pyshell#20>", line 1, in <module>
    abc
NameError: name 'abc' is not defined
>>> print 'xioayi'
SyntaxError: Missing parentheses in call to 'print'. Did you mean print('xioayi')?
>>> 1 + '1'
Traceback (most recent call last):
  File "<pyshell#22>", line 1, in <module>
    1 + '1'
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> 6 / 0
Traceback (most recent call last):
  File "<pyshell#23>", line 1, in <module>
    6 / 0
ZeroDivisionError: division by zero
>>> 

为了减少我们的异常或者说是检测异常我们会在程序中使用异常检测语句:

1、try -except语句

语句模式:

try:

             检测范围

except  Exception[as  reason]:

            出现异常(Exception)后的处理代码

try:
      f = open('xiaoyi.text')
      print(f.read())
      f.close()
except OSError:
      print('文件出错')
      

当然我们也可以打印出出错的原因:

try:
      f = open('xiaoyi.text')
      print(f.read())
      f.close()
except OSError as reason:
      print('文件出错\n错误的原因是:'  + str(reason))
      

我们看一下运行结果:

文件出错
错误的原因是:[Errno 2] No such file or directory: 'xiaoyi.text'
>>> 

当然一个人try也是可以和多个except配合使用的:

try:
      sum = 1 + '1'
      f = open('xiaoyi.text')
      print(f.read())
      f.close()
except OSError as reason:
      print('文件出错\n错误的原因是:'  + str(reason))
      
except TypeError as reason:
      print('类型出错\n错误的原因是:'  + str(reason))

我们看一下这个运行结果:

类型出错
错误的原因是:unsupported operand type(s) for +: 'int' and 'str'
>>> 

从这两个运行结果中我们可以看出try语句一旦遇到一个错误下面的代码就不会执行了。

还有一种写法也是可以的:

try:
      sum = 1 + '1'
      f = open('xiaoyi.text')
      print(f.read())
      f.close()
except (OSError,TypeError):
      print('出错\n')
      

     

2、try -  finally语句

语句格式:

try:

               检测范围

except  Exception [as reason]:

                出现异常(Exception)后的处理代码

finally:

               无论如何人都会被执行的代码

try:
      f = open('xiaoyi.text' ,'w')
      print(f.write('创建成功'))
      sum = 1 + '1'
      f.close()
except (OSError,TypeError):
      print('出错\n')
finally:     
      f.close()
     

从上面的代码我们可以看出,如果我们没有写finally语句的话,是不能将内容写到文件中的,因为try后面的关闭文件语句close是执行不了的,这样我们写的内容就一直在缓冲区中,只有关闭文件才会写到文件中,finally帮助我们做到了。

我们也可以使用raise引出一个异常:

>>> raise ZeroDivisionError
Traceback (most recent call last):
  File "<pyshell#25>", line 1, in <module>
    raise ZeroDivisionError
ZeroDivisionError
>>> raise ZeroDivisionError ('除数异常')
Traceback (most recent call last):
  File "<pyshell#26>", line 1, in <module>
    raise ZeroDivisionError ('除数异常')
ZeroDivisionError: 除数异常
>>> 

try语句也是可以配合else使用的 :

try:
      int('abc')
except ValueError as reason:
      print('出错了\n异常是:' + str(reason))
else:     
      print('没有出现异常 ')
     

使用with语句可以简化我们的代码 :

try:
      with open('xiaoyi.text' ,'w') as f:
            for each_line in f:
                  print(each_line)
except OSError:
      print('出错\n')
finally:
      f.close()

 

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值