在Python中手动引发(抛出)异常

发布于 2021-02-02 23:19:37

如何在Python中引发异常,以便以后可以通过except块将其捕获?

关注者
0
被浏览
100
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    在你的消息中要具体,例如:

    raise ValueError('A very specific bad thing happened.')
    

    不要引发通用异常

    避免提出泛型Exception。要捕获它,你必须捕获将其子类化的所有其他更具体的异常。

    问题1:隐藏错误

    raise Exception('I know Python!') # Don't! If you catch, likely to hide bugs.
    

    例如:

    def demo_bad_catch():
        try:
            raise ValueError('Represents a hidden bug, do not catch this')
            raise Exception('This is the exception you expect to handle')
        except Exception as error:
            print('Caught this error: ' + repr(error))
    
    >>> demo_bad_catch()
    Caught this error: ValueError('Represents a hidden bug, do not catch this',)
    

    问题2:无法抓住

    而且更具体的捕获不会捕获一般异常:

    def demo_no_catch():
        try:
            raise Exception('general exceptions not caught by specific handling')
        except ValueError as e:
            print('we will not catch exception: Exception')
    
    
    >>> demo_no_catch()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 3, in demo_no_catch
    Exception: general exceptions not caught by specific handling
    

    最佳做法:raise声明

    而是使用在语义上适合你的issue的最特定的Exception构造函数。

    raise ValueError('A very specific bad thing happened')
    

    这也方便地允许将任意数量的参数传递给构造函数:

    raise ValueError('A very specific bad thing happened', 'foo', 'bar', 'baz') 
    

    这些参数由对象args上的属性访问Exception。例如:

    try:
        some_code_that_may_raise_our_value_error()
    except ValueError as err:
        print(err.args)
    

    版画

    ('message', 'foo', 'bar', 'baz')   
    

    在Python 2.5中,message添加了一个实际属性,以·鼓励用户继承Exceptions子类并停止使用args,但args 的引入message和最初的弃用已被收回。

    最佳做法:except条款

    例如,在except子句中时,你可能想要记录发生了特定类型的错误,然后重新引发。在保留堆栈跟踪的同时执行此操作的最佳方法是使用裸机抬高语句。例如:

    logger = logging.getLogger(__name__)
    
    try:
        do_something_in_app_that_breaks_easily()
    except AppError as error:
        logger.error(error)
        raise                 # just this!
        # raise AppError      # Don't do this, you'll lose the stack trace!
    

    不要修改你的错误…但是如果你坚持的话。
    你可以使用来保留stacktrace(和错误值)sys.exc_info(),但这更容易出错,并且在Python 2和3之间存在兼容性问题,建议使用裸机raise重新引发。

    解释- sys.exc_info()返回类型,值和回溯。

    type, value, traceback = sys.exc_info()
    

    这是Python 2中的语法-请注意,这与Python 3不兼容:

        raise AppError, error, sys.exc_info()[2] # avoid this.
        # Equivalently, as error *is* the second object:
        raise sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]
    

    如果愿意,你可以修改新加薪时发生的情况-例如args,为实例设置新值:

    def error():
        raise ValueError('oops!')
    
    def catch_error_modify_message():
        try:
            error()
        except ValueError:
            error_type, error_instance, traceback = sys.exc_info()
            error_instance.args = (error_instance.args[0] + ' <modification>',)
            raise error_type, error_instance, traceback
    

    并且我们在修改args时保留了整个回溯。请注意,这不是最佳做法,并且在Python 3中是无效语法(使保持兼容性变得更加困难)。

    >>> catch_error_modify_message()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 3, in catch_error_modify_message
      File "<stdin>", line 2, in error
    ValueError: oops! <modification>
    

    在Python 3中:

    raise error.with_traceback(sys.exc_info()[2])
    

    再次:避免手动操作回溯。它效率较低,更容易出错。而且,如果你正在使用线程,sys.exc_info甚至可能会得到错误的回溯(特别是如果你对控制流使用异常处理,我个人倾向于避免这种情况。)

    Python 3,异常链接

    在Python 3中,你可以链接异常,以保留回溯:

      raise RuntimeError('specific message') from error
    

    意识到:

    • 这确实允许更改引发的错误类型,并且
    • 这与Python 2 不兼容。

    不推荐使用的方法:

    这些可以轻松隐藏甚至进入生产代码。你想提出一个例外,而这样做会引发一个例外,但不是一个预期的例外!

    在Python 2中有效,但在Python 3中无效:

    raise ValueError, 'message' # Don't do this, it's deprecated!
    

    仅在更旧的Python版本(2.4及更低版本)中有效,你可能仍然会看到有人在引发字符串:

    raise 'message' # really really wrong. don't do this.
    

    在所有现代版本中,这实际上会引发一个TypeError,因为你没有引发一个BaseException类型。如果你没有检查正确的例外情况,并且没有知道该问题的审阅者,那么它可能会投入生产。

    用法示例

    我提出异常,以警告使用者如果我的API使用不正确:

    适当时创建自己的错误类型

    “我想故意犯一个错误,以便将其排除在外”

    你可以创建自己的错误类型,如果你想指出应用程序中某些特定的错误,只需在异常层次结构中将适当的点子类化:

    class MyAppLookupError(LookupError):
        '''raise this when there's a lookup error for my app'''
    和用法:
    
    if important_key not in resource_dict and not ok_to_be_missing:
        raise MyAppLookupError('resource is missing, and that is not ok.')
    


  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    不能得到比这更多的pythonic:

    raise Exception("I know python!")
    

    如果你需要更多信息,请参阅关于Python 的凸起语句文档。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看