Python中的异常处理讲解

来自:网络
时间:2022-05-28
阅读:
目录

一、什么是异常

在python中,错误触发的异常如下

Python中的异常处理讲解

二、异常的种类

在python中不同的异常可以用不同的类型去标识,一个异常标识一种错误。

1 、常用异常类

  • AttributeError 试图访问一个对象没有的树形,比如foo.x,但是foo没有属性x
  • IOError 输入/输出异常;基本上是无法打开文件
  • ImportError 无法引入模块或包;基本上是路径问题或名称错误
  • IndentationError 语法错误(的子类) ;代码没有正确对齐
  • IndexError 下标索引超出序列边界,比如当x只有三个元素,却试图访问x[5]
  • KeyError 试图访问字典里不存在的键
  • KeyboardInterrupt Ctrl+C被按下
  • NameError 使用一个还未被赋予对象的变量
  • SyntaxError Python代码非法,代码不能编译(个人认为这是语法错误,写错了)
  • TypeError 传入对象类型与要求的不符合
  • UnboundLocalError 试图访问一个还未被设置的局部变量,基本上是由于另有一个同名的全局变量,导致你以为正在访问它
  • ValueError 传入一个调用者不期望的值,即使值的类型是正确的

2、异常举例:

# TypeError:int类型不可迭代
for i in 3:
    pass

# ValueError
num=input(">>: ") #输入hello
int(num)

# NameError
aaa

# IndexError
l=['egon','aa']
l[3]

# KeyError
dic={'name':'egon'}
dic['age']

# AttributeError
class Foo:pass
Foo.x

# ZeroDivisionError:无法完成计算
res1=1/0
res2=1+'str'

三、异常处理

1、基本语法try...except

try:
    被检测的代码块
except 异常类型:
    try中一旦检测到异常,就执行这个位置的逻辑

举例

try:
    f = [ 'a', 'a', 'a','a','a', 'a','a',]
    g = (line.strip() for line in f) #元组推导式
    print(next(g))
    print(next(g))
    print(next(g))
    print(next(g))
    print(next(g))
except StopIteration:
    f.close()

异常类只能用来处理指定的异常情况,如果非指定异常则无法处理。

s1 = 'hello'
try:
    int(s1)
except IndexError as e:  # 未捕获到异常,程序直接报错
    print(e)

2、多分支异常 except..except与万能异常:Exception

s1 = 'hello'
try:
    int(s1)
except IndexError as e:
    print(e)
except KeyError as e:
    print(e)
except ValueError as e:
    print(e)
except Exception as e:
    print(e)

3、try/except...else

try/except 语句还有一个可选的 else 子句,如果使用这个子句,那么必须放在所有的 except 子句之后。

else 子句将在 try 子句没有发生任何异常的时候执行。

for arg in sys.argv[1:]:
    try:
        f = open(arg, 'r')
    except IOError:
        print('cannot open', arg)
    else:
        print(arg, 'has', len(f.readlines()), 'lines')
        f.close()

4、异常的最终执行finally

try-finally 语句无论是否发生异常都将执行最后的代码。

定义清理行为:

s1 = 'hello'
try:
    int(s1)
except IndexError as e:
    print(e)
except KeyError as e:
    print(e)
except ValueError as e:
    print(e)
#except Exception as e:
#    print(e)
else:
    print('try内代码块没有异常则执行我')
finally:
    print('无论异常与否,都会执行该模块,通常是进行清理工作')

#invalid literal for int() with base 10: 'hello'

#无论异常与否,都会执行该模块,通常是进行清理工作

四、抛出异常raise

Python 使用 raise 语句抛出一个指定的异常。

raise语法格式如下:

raise [Exception [, args [, traceback]]]
try:
    raise TypeError('抛出异常,类型错误')
except Exception as e:
    print(e)

raise 唯一的一个参数指定了要被抛出的异常。它必须是一个异常的实例或者是异常的类(也就是 Exception 的子类)。

如果你只想知道这是否抛出了一个异常,并不想去处理它,那么一个简单的 raise 语句就可以再次把它抛出。

try:
        raise NameError('HiThere')
    except NameError:
        print('An exception flew by!')
        raise
   
#An exception flew by!
#Traceback (most recent call last):
#  File "", line 2, in ?
#NameError: HiThere

五、自定义异常

你可以通过创建一个新的异常类来拥有自己的异常。异常类继承自 Exception 类,可以直接继承,或者间接继承,例如:

在这个例子中,类 Exception 默认的 __init__() 被覆盖。

class EgonException(Exception):
    def __init__(self, msg):
        self.msg = msg

    def __str__(self):
        return self.msg


try:
    raise EgonException('抛出异常,类型错误')
except EgonException as e:
    print(e) 

#抛出异常,类型错误

基础异常类

当创建一个模块有可能抛出多种不同的异常时,一种通常的做法是为这个包建立一个基础异常类,然后基于这个基础类为不同的错误情况创建不同的子类:

大多数的异常的名字都以"Error"结尾,就跟标准的异常命名一样。

class Error(Exception):
    """Base class for exceptions in this module."""
    pass
 
class InputError(Error):
    """Exception raised for errors in the input.
 
    Attributes:
        expression -- input expression in which the error occurred
        message -- explanation of the error
    """
 
    def __init__(self, expression, message):
        self.expression = expression
        self.message = message
 
class TransitionError(Error):
    """Raised when an operation attempts a state transition that's not
    allowed.
 
    Attributes:
        previous -- state at beginning of transition
        next -- attempted new state
        message -- explanation of why the specific transition is not allowed
    """
 
    def __init__(self, previous, next, message):
        self.previous = previous
        self.next = next
        self.message = message

六、断言assert

assert(断言)用于判断一个表达式,在表达式条件为 false 的时候触发异常。

断言可以在条件不满足程序运行的情况下直接返回错误,而不必等待程序运行后出现崩溃的情况。

语法格式如下:

assert expression

等价于:

if not expression:
    raise AssertionError

assert 后面也可以紧跟参数:

assert expression [, arguments]

等价于:

if not expression:
    raise AssertionError(arguments)

以下实例判断当前系统是否为 Linux,如果不满足条件则直接触发异常,不必执行接下来的代码:

import sys
assert ('linux' in sys.platform), "该代码只能在 Linux 下执行"
# 接下来要执行的代码

# Traceback (most recent call last):
#    File "C:/PycharmProjects/untitled/run.py", line 2, in 
#      assert ('linux' in sys.platform), "该代码只能在 Linux 下执行"
#  AssertionError: 该代码只能在 Linux 下执行

到此这篇关于Python异常处理的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持。

返回顶部
顶部