前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python: 异常处理

Python: 异常处理

作者头像
用户2183996
发布2018-06-21 17:47:50
6030
发布2018-06-21 17:47:50
举报
文章被收录于专栏:技术沉淀技术沉淀技术沉淀

1. 扑获异常

1.1 基本语法

把可能抛出异常(出错)的语句放在tryblock里,然后用except去扑捉(预判)可能的异常类型,如果异常类型match,就执行except模块。

try:
    # write some code
    # that might throw exception
except <ExceptionType>:
    # Exception handler, alert the user

比如读取一个不存在的文件会引起IOError,我们就可以提前加以处理。

try:
    f = open('nofile.txt', 'r')
    print f.read()
    f.close()
except IOError:
    print 'file not found'
file not found

执行流程是这样的:

  1. First statement between try and except block are executed.
  2. If no exception occurs then code under except clause will be skipped.
  3. If file don’t exists then exception will be raised and the rest of the code in the try block will be skipped
  4. When exceptions occurs, if the exception type matches exception name after except keyword, then the code in that except clause is executed.

1.2 扑获更多异常类型

try:
    <body>
except <ExceptionType1>:
    <handler1>
except <ExceptionTypeN>:
    <handlerN>
except:
    <handlerExcept>
else:
    <process_else>
finally:
    <process_finally>
  1. except类似于elif,当try出现异常时,挨个匹配except里的异常类型,如果匹配,执行;若果没有匹配,执行不指定异常类型的except
  2. else只有在try执行时没有异常的时候执行。
  3. finally不管try模块是否有异常抛出,都执行。

1.3 例子

num1, num2 = 1,0
try:
    result = num1 / num2
    print("Result is", result)

except ZeroDivisionError:
    print("Division by zero is error !!")

except:
    print("Wrong input")

else:
    print("No exceptions")

finally:
    print("This will execute no matter what you input")
Division by zero is error !!
This will execute no matter what you input

2. 抛出异常

raise语句抛出自己的异常。raise ExceptionClass('Your argument')

def enterage(age):
    if age < 0:
        raise ValueError("Only positive integers are allowed")

    if age % 2 == 0:
        print("age is even")

try:
    num = int(input("Enter your age: "))
    enterage(num)
except ValueError:
    print 'Only positive integers are allowd'
except:
    print 'Something went wrong'
Enter your age: -3
Only positive integers are allowd

异常参考图,更多异常类型参见官方文档

exception

3. 操作异常

有时候我们希望能把异常对象传递给一个变量,也非常方便实现。

try:
    # this code is expected to throw exception
except ExceptionType as ex:
    # code to handle exception
try:
    number = int(input("Enter a number: "))
    print "The number entered is", number

except NameError as ex:
    print "Exception:", ex
Enter a number: one
Exception: name 'one' is not defined
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016.07.11 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. 扑获异常
    • 1.1 基本语法
      • 1.2 扑获更多异常类型
        • 1.3 例子
        • 2. 抛出异常
          • 3. 操作异常
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档