详解在Python程序中自定义异常的方法

yipeiwu_com5年前Python基础

通过创建一个新的异常类,程序可以命名它们自己的异常。异常应该是典型的继承自Exception类,通过直接或间接的方式。
以下为与RuntimeError相关的实例,实例中创建了一个类,基类为RuntimeError,用于在异常触发时输出更多的信息。
在try语句块中,用户自定义的异常后执行except块语句,变量 e 是用于创建Networkerror类的实例。

class Networkerror(RuntimeError):
  def __init__(self, arg):
   self.args = arg

在你定义以上类后,你可以触发该异常,如下所示:

try:
  raise Networkerror("Bad hostname")
except Networkerror,e:
  print e.args

在下面这个例子中,默认的__init__()异常已被我们重写。

>>> class MyError(Exception):
...   def __init__(self, value):
...     self.value = value
...   def __str__(self):
...     return repr(self.value)
...
>>> try:
...   raise MyError(2*2)
... except MyError as e:
...   print 'My exception occurred, value:', e.value
...
My exception occurred, value: 4
>>> raise MyError, 'oops!'
Traceback (most recent call last):
 File "<stdin>", line 1, in ?
__main__.MyError: 'oops!'

常见的做法是创建一个由该模块定义的异常基类和子类,创建特定的异常类不同的错误条件。

我们通常定义的异常类,会让它比较简单,允许提取异常处理程序的错误信息,当创建一个异常模块的时候,常见的做法是创建一个由该模块定义的异常基类和子类,根据不同的错误条件,创建特定的异常类:

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

相关文章

docker-py 用Python调用Docker接口的方法

docker-py 用Python调用Docker接口的方法

官方文档:【https://docker-py.readthedocs.io/en/stable/images.html】 众所周知,Docker向外界提供了一个API来管理其中的资源。...

Python进程间通信之共享内存详解

前一篇博客说了怎样通过命名管道实现进程间通信,但是要在windows是使用命名管道,需要使用python调研windows api,太麻烦,于是想到是不是可以通过共享内存的方式来实现。查...

Django+JS 实现点击头像即可更改头像的方法示例

Django+JS 实现点击头像即可更改头像的方法示例

首先,在models.py中创建UserModels类 from django.db import models from django.contrib.auth.models im...

Python2.7实现多进程下开发多线程示例

简单的基于Python2.7版本的多进程下开发多线程的示例,供大家参考,具体内容如下 可以使得程序执行效率至少提升10倍 #!/usr/bin/env python # -*- co...

Python实现Mysql数据库连接池实例详解

Python实现Mysql数据库连接池实例详解

python连接Mysql数据库: Python编程中可以使用MySQLdb进行数据库的连接及诸如查询/插入/更新等操作,但是每次连接MySQL数据库请求时,都是独立的去请求访问,相当...