python——异常

一、异常是什么?

  • python提供功能强大的替代解决方案——异常处理机制
  • python使用异常对象来表示异常状态,并在遇到错误时引发异常
  • 异常对象未被处理(或捕获)时,程序将终止并显示一条错误消息(traceback)。
  • 异常不止是用来显示错误消息,事实上,每个异常都是某个类的实例。你能以各种方式引发和捕获这些实例,从而逮住错误并采取措施,而不是放任整个程序失败。

二、raise语句和自定义异常类

2.1raise语句
要引发异常,可使用raise语句,并将一个类或实例作为参数。将类作为参数时,将自动创建一个实例。

# 通用异常,没有指出出现什么错误
raise Exception
# Exception

# 添加了错误消息hyperdrive overload
raise Exception('hyperdrive overload')
# Exception: hyperdrive overload

很多内置的异常类,都可用于raise语句。

2.2自定义的异常类
虽然内置异常类涉及范围广,能够满足很多需求,但有时你可能想自己创建异常类。
如何创建异常类?就像创建其他类一样,但必须直接或间接的继承Exception(这意味着从任何内置异常类派生都可以)。

class SomeCustomException(Exception):
    pass

三、捕获异常

捕获异常就是对异常进行处理。可使用try/except。

x = int(input('input the first number:'))
y = int(input('input the second number:'))
print(x/y)
# input the first number:10
# input the second number:0
# ZeroDivisionError: division by zero

# 为了捕获这种异常并对错误进行处理
try:
    x = int(input('input the first number:'))
    y = int(input('input the second number:'))
    print(x / y)
except ZeroDivisionError:
    print("The second number can't be zero!")
# input the first number:10
# input the second number:0
# The second number can't be zero!

3.1不用提供参数

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值