八、异 常


8.1 异常是什么

Python使用异常对象来表示异常状态,并在遇到错误时引发异常。


8.2 自主引发异常

8.2.1 raise语句

>>> raise Exception
Traceback (most recent call last):
  File "E:/Ppractice/Ppython/test/test.py", line 1, in <module>
    raise Exception
Exception

8.2.2 自定义的异常类

class SomeCustomException(Exception):pass

8.3 捕获异常

try:
    x = int(input('Enter the first number:'))
    y = int(input('Enter the second numbrt:'))
    print(x / y)
except ZeroDivisionError:
    print("The second number can't be zero!")

8.3.1 多个except子句

try:
    x = int(input('Enter the first number:'))
    y = int(input('Enter the first number:'))
    print(x / y)
except ZeroDivisionError:
    print("The second number can't be zero!")
except TypeError:
    print("That wasn't a number,was it?")

8.3.2 一个except子句捕获多种异常

try:
    x = int(input('Enter the first number:'))
    y = int(input('Enter the first number:'))
    print(x / y)
except (ZeroDivisionError, TypeError, NameError):
    print("Your numbers were bogus...")

8.3.3 捕获对象

需要让程序继续运行并记录错误时,这很有用。

try:
    x = int(input('Enter the first number:'))
    y = int(input('Enter the first number:'))
    print(x / y)
except (ZeroDivisionError, TypeError) as e:
    print(e)

8.3.4 最后

finally子句,可用于在发生异常时执行清理工作。

x = None
try:
   x = 1/0
finally:
   print('Cleaning up...')
   del x

8.4 异常和函数

def faulty():
    raise Exception('Something is wrong')
    
def handle_exception():
    try:
        faulty()
    except:
        print('Exception handled')
>>> handle_exception()
Exception handled

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值