python中的异常处理

目录

一:处理机制

二:实例


一:处理机制

Python中的异常处理主要通过try/except语句实现。try语句块包含可能会引发异常的代码,而except语句块包含在try块中发生异常时要执行的代码。此外,Python还提供了一个finally语句块,无论try块中的代码是否引发异常,finally块中的代码都会被执行。这可以用来进行一些清理工作,例如关闭文件或释放资源等。

二:实例



(一)处理异常
#-*- coding:utf-8 -*-

import time
import sys
'''
try:
    s = raw_input('Enter something --> ')
except EOFError:
    print '\nWhy did you do an EOF on me?'
    sys.exit() # exit the program
except:
    print '\nSome error/exception occurred.'
    # here, we are not exiting the program

print 'Done'

#把所有可能引发错误的语句放在try块中
#在except从句/块中处理所有的错误和异常


(二)引发异常

#创建自己的异常类

class ShortInputException(Exception):#继承Exception类
    '''A user-defined exception class.'''
    def __init__(self, length, atleast):  #length是给定输入的长度,atleast则是程序期望的最小长度。
        Exception.__init__(self)
        self.length = length
        self.atleast = atleast

try:
    s = raw_input('please input str:')
    if len(s) < 3:
        raise ShortInputException(len(s), 3) #用raise引发异常
except EOFError:
    print '\nWhy did you do an EOF on me?'
except ShortInputException, x:
    print 'ShortInputException: The input was of length %d, \
       # was expecng at least %d' % (x.length, x.atleast)
else
            print 'No exception was raised.'
'''

(三)try..finally
#你在读一个文件的时候,希望在无论异常发生与否的情况下都关闭文件


try:
    f = file('1.txt')
    while True: # our usual file-reading idiom
        line = f.readline()
        if len(line) == 0:
            break
        time.sleep(2)
        print line,
finally:
    f.close()
    print 'Cleaning up...closed the file




   
 

相关推荐

  1. Python 异常处理

    2024-01-08 11:00:07       41 阅读
  2. Python异常处理

    2024-01-08 11:00:07       22 阅读
  3. Python错误和异常处理

    2024-01-08 11:00:07       11 阅读
  4. Python异常处理

    2024-01-08 11:00:07       14 阅读
  5. Python程序异常处理解决方法

    2024-01-08 11:00:07       34 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-01-08 11:00:07       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-08 11:00:07       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-08 11:00:07       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-08 11:00:07       18 阅读

热门阅读

  1. Js进阶29-正则表达式专题

    2024-01-08 11:00:07       27 阅读
  2. 回溯算法part02 算法

    2024-01-08 11:00:07       38 阅读
  3. 修复。。。Github/Gitee 提交推送没有贡献度小绿点

    2024-01-08 11:00:07       35 阅读
  4. 【排序算法】删除有序数组中的重复项 II

    2024-01-08 11:00:07       26 阅读
  5. Go 类型系统

    2024-01-08 11:00:07       37 阅读
  6. Timsort:最快排序算法

    2024-01-08 11:00:07       35 阅读
  7. React router

    2024-01-08 11:00:07       38 阅读
  8. 《微信小程序开发从入门到实战》学习七十五

    2024-01-08 11:00:07       28 阅读
  9. C#-基本概念

    2024-01-08 11:00:07       23 阅读
  10. 一级建造师大纲变化,我们该如何备考?

    2024-01-08 11:00:07       29 阅读
  11. nacos与eureka区别

    2024-01-08 11:00:07       35 阅读
  12. 《母亲的纯净水》

    2024-01-08 11:00:07       28 阅读