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