Python: 异常处理

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
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值