实现python异常 [英] Implementing python exceptions

查看:97
本文介绍了实现python异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在程序中执行异常系统时遇到了一些问题。
我发现我试图用于我的程序的以下代码片段:

I'm having some problems implementing an exception system in my program. I found somewhere the following piece of code that I am trying to use for my program:

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

我认为msg必须是要显示的字符串消息,但是当我想提出此异常时如何填写expr?我必须用手写吗?

I think msg must be a string message to be shown, but how do I fill the "expr" when I want to raise this exception? Do I have to write it by hand?

raise InvalidProgramStateException(what_here?, "there was an error")


推荐答案

您的自定义异常实际上根本不需要参数。如果你没有任何特定的错误消息或状态来封装在异常中,这将很正常:

Your custom exceptions don't actually need to take parameters at all. If you haven't got any particular error message or state to encapsulate in the Exception, this will work just fine:

class MyException(Exception):
    pass

这将允许您的程序捕获此异常的情况键入:

This would allow your program to catch cases of this exception by type:

try:
    raise MyException()
except MyException:
    print "Doing something with MyException"
except:
    print "Some other error occurred... handling it differently"

如果您希望异常具有一些有意义的字符串表示形式,或者具有为您的应用程序提供更多关于出错问题的详细信息的属性,那么当您向构造函数传递其他参数时。这些参数的数量,名称和类型不是真正由Python预定义的...它们可以是任何东西。只需确保提供自定义的 __ str __ __ unicode __ 方法,以便您可以提供有意义的文字描述:

If you want the Exception to have some meaningful string representation, or have properties that would provide your application greater details on what went wrong, that's when you pass additional arguments to the constructor. The number, name and type of these arguments is not really pre-defined by Python... they can be anything. Just be sure to provide a custom __str__ or __unicode__ method so you can provide a meaningful text depiction:

class MyException(Exception):

    def __init__(self, msg):
        self.msg = msg

    def __str__(self):
        return "MyException with %s" % self.msg

在您引用的示例的情况下, expr msg 参数特定于示例的虚构情况。对于如何使用这些可能性的设想方案是:

In the case of the example you're quoting, the expr and msg parameters are specific to the fictional case of the example. A contrived scenario for how these might be used is:

def do_something(expr):
    if 'foo' in expr:
        raise InvalidProgramStateException(expr, "We don't allow foos here")
    return 5

user_input = 'foo bar'
try:
    do_something(user_input)
except InvalidProgramStateException, e:
    print "%s (using expression %s)" % (e.msg, e.expr)

由于您的应用程序不需要它,只需删除不需要的参数。

Since it doesn't appear that your application requires it, just drop the parameters you don't require.

这篇关于实现python异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆