Python异常

什么是异常

异常即是一个事件,该事件会在程序执行过程中发生,影响了程序的正常执行。 一般情况下,在Python无法正常处理程序时就会发生一个异常。 异常是Python对象,表示一个错误。 当Python脚本发生异常时我们需要捕获处理它,否则程序会终止执行。

常见异常类型

异常名称描述
FileNotFoundError找不到指定文件的异常
NameError未声明/初始化对象(没有属性)
BaseException所有异常的基类

异常处理语句

  • try...except...
  • try...except...finally
  • raise

 

1、try...except

FileNotFoundError

#找不到指定文件的异常
 try:
     fileName=input("Please input the filename:")
     open("%r.txt" %fileName)
 except FileNotFoundError:
     print("File not found!")

NameError

#未声明/初始化对象(没有属性)
 try:
     print(stu)
 except NameError:
     print("变量未定义")

BaseException

 try:
     print(stu)
 except BaseException:
     print("变量未定义")

try...except...as

 try:
#     stu='Nancy'
     print(stu)
 except BaseException as msg:
     print(msg)

try...except...else使用

 try:
#     stu='Nancy'
     print(stu)
 except BaseException as msg:
     print(msg)
 else:
     print("stu is defined!")

2、try...except...finally输出

 try:
     stu='Nancy'
     print(stu)
 except BaseException as msg:
     print(msg)
 else:
     print("stu is defined!")
 finally:
     print("The end!")

3、raise抛出异常

前面try语句是执行过程中捕获代码块的异常,而raise是通过事先定义一个条件,一旦符合异常条件就抛出异常。

def division(x,y):
    if y==0:
     raise ZeroDivisionError("Zero is not allowed!")
    else:
        return x/y
try:
    division(8,0)
except BaseException as msg:
    print(msg)

 

 

 

转载于:https://www.cnblogs.com/NancyRM/p/8038461.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值