全班的例外 [英] Exceptions for the whole class

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

问题描述

我在Python中编写一个程序,几乎所有的类都是这样写的:

  def someMethod (self):
try:
#...
except someException:
#in case of exception,do something here

#eg显示一个对话框通知用户
#他做错了

随着课程增长,一遍又一遍写出相同的try-except块是有点恼人的。是否有可能为整个类创建某种全局异常? Python中的建议方法是什么?

解决方案

编写一个或多个异常处理程序函数,给定一个函数和其中引发的异常,执行您要执行的操作(例如显示警报)。如果您需要多于一个,请写下。

  def message(func,e):
printException ,type(e).__ name__,in,func .__ name__
print str(e)

现在写一个将给定处理程序应用于调用函数的装饰器:

  import functools 

def handle_with(handler,* exceptions):
try:
处理程序,cleanup = handler
除了TypeError:
cleanup = lambda f,e:无
def decorator (func):
@ functools.wraps(func)
def wrapper(* args,** kwargs):
try:
return func(* args,** kwargs)
除了异常或异常作为e:
返回处理程序(func,e)
最终:
清理(func,e)
返回包装器
返回装饰器

这仅捕获您指定的异常。如果您没有指定任何内容,则会捕获异常。另外,第一个参数可以是两个处理函数的元组(或其他序列);第二个处理程序(如果给出)在 finally 子句中调用。从主处理程序返回的值作为函数调用的值返回。



现在,如上所述,您可以写:

  @handle_with(message,TypeError,ValueError)
def add(x,y):
return x + y

您还可以使用上下文管理器执行此操作:

  from contextlib import contextmanager 

@contextmanager
def handler(handler,* exceptions):
try:
handler,cleanup = handler
除了TypeError:
cleanup = lambda e:无
try:
yield
除了异常或异常作为e:
处理程序(e)
最后:
清理(e)

现在你可以写:

  def message(e):
printException,type(e).__ name__
print str(e)

def add(x,y):
with handler(message,TypeError,ValueError):
re转换x + y

请注意,上下文管理器不知道它的功能(你可以找到这个,sorta,使用 inspect ,虽然这是魔术,所以我没有这样做),所以它给你一些不太有用的信息。此外,上下文管理器不给您机会在您的处理程序中返回任何内容。


I'm writing a program in Python, and nearly every method im my class is written like this:

def someMethod(self):
    try:
       #...
    except someException:
       #in case of exception, do something here

       #e.g display a dialog box to inform the user 
       #that he has done something wrong

As the class grows, it is a little bit annoying to write the same try-except block over and over. Is it possible to create some sort of 'global' exception for the whole class? What's the recommended way in Python to deal with this?

解决方案

Write one or more exception handler functions that, given a function and the exception raised in it, does what you want to do (e.g. displays an alert). If you need more than one, write them.

def message(func, e):
    print "Exception", type(e).__name__, "in", func.__name__
    print str(e)

Now write a decorator that applies a given handler to a called function:

import functools

def handle_with(handler, *exceptions):
    try:
        handler, cleanup = handler
    except TypeError:
        cleanup = lambda f, e: None
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            try:
                return func(*args, **kwargs)
            except exceptions or Exception as e:
                return handler(func, e)
            finally:
                cleanup(func, e)
        return wrapper
    return decorator

This only captures the exceptions you specify. If you don't specify any, Exception is caught. Additionally, the first argument can be a tuple (or other sequence) of two handler functions; the second handler, if given, is called in a finally clause. The value returned from the primary handler is returned as the value of the function call.

Now, given the above, you can write:

@handle_with(message, TypeError, ValueError)
def add(x, y):
    return x + y

You could also do this with a context manager:

from contextlib import contextmanager 

@contextmanager
def handler(handler, *exceptions):
    try:
        handler, cleanup = handler
    except TypeError:
        cleanup = lambda e: None
    try:
        yield
    except exceptions or Exception as e:
        handler(e)
    finally:
        cleanup(e)

Now you can write:

def message(e):
    print "Exception", type(e).__name__
    print str(e)

 def add(x, y):
     with handler(message, TypeError, ValueError):
         return x + y

Note that the context manager doesn't know what function it's in (you can find this out, sorta, using inspect, though this is "magic" so I didn't do it) so it gives you a little less useful information. Also, the context manager doesn't give you the opportunity to return anything in your handler.

这篇关于全班的例外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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