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

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

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

How can I raise an exception in Python so that it can later be caught via an except block?


回答 0

如何在Python中手动引发/引发异常?

使用在语义上适合您的问题的最特定的Exception构造函数

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

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添加了一个实际属性,以BaseException鼓励用户继承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 兼容。

不推荐使用的方法:

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

在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类型。如果您没有检查正确的exceptions情况,并且没有知道此问题的审阅者,那么它可能会投入生产。

用法示例

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

def api_func(foo):
    '''foo should be either 'baz' or 'bar'. returns something very useful.'''
    if foo not in _ALLOWED_ARGS:
        raise ValueError('{foo} wrong, use "baz" or "bar"'.format(foo=repr(foo)))

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

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

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

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.')

How do I manually throw/raise an exception in Python?

Use the most specific Exception constructor that semantically fits your issue.

Be specific in your message, e.g.:

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

Don’t raise generic exceptions

Avoid raising a generic Exception. To catch it, you’ll have to catch all other more specific exceptions that subclass it.

Problem 1: Hiding bugs

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

For example:

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',)

Problem 2: Won’t catch

And more specific catches won’t catch the general exception:

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

Best Practices: raise statement

Instead, use the most specific Exception constructor that semantically fits your issue.

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

which also handily allows an arbitrary number of arguments to be passed to the constructor:

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

These arguments are accessed by the args attribute on the Exception object. For example:

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

prints

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

In Python 2.5, an actual message attribute was added to BaseException in favor of encouraging users to subclass Exceptions and stop using args, but the introduction of message and the original deprecation of args has been retracted.

Best Practices: except clause

When inside an except clause, you might want to, for example, log that a specific type of error happened, and then re-raise. The best way to do this while preserving the stack trace is to use a bare raise statement. For example:

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!

Don’t modify your errors… but if you insist.

You can preserve the stacktrace (and error value) with sys.exc_info(), but this is way more error prone and has compatibility problems between Python 2 and 3, prefer to use a bare raise to re-raise.

To explain – the sys.exc_info() returns the type, value, and traceback.

type, value, traceback = sys.exc_info()

This is the syntax in Python 2 – note this is not compatible with 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]

If you want to, you can modify what happens with your new raise – e.g. setting new args for the instance:

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

And we have preserved the whole traceback while modifying the args. Note that this is not a best practice and it is invalid syntax in Python 3 (making keeping compatibility much harder to work around).

>>> 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>

In Python 3:

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

Again: avoid manually manipulating tracebacks. It’s less efficient and more error prone. And if you’re using threading and sys.exc_info you may even get the wrong traceback (especially if you’re using exception handling for control flow – which I’d personally tend to avoid.)

Python 3, Exception chaining

In Python 3, you can chain Exceptions, which preserve tracebacks:

    raise RuntimeError('specific message') from error

Be aware:

  • this does allow changing the error type raised, and
  • this is not compatible with Python 2.

Deprecated Methods:

These can easily hide and even get into production code. You want to raise an exception, and doing them will raise an exception, but not the one intended!

Valid in Python 2, but not in Python 3 is the following:

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

Only valid in much older versions of Python (2.4 and lower), you may still see people raising strings:

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

In all modern versions, this will actually raise a TypeError, because you’re not raising a BaseException type. If you’re not checking for the right exception and don’t have a reviewer that’s aware of the issue, it could get into production.

Example Usage

I raise Exceptions to warn consumers of my API if they’re using it incorrectly:

def api_func(foo):
    '''foo should be either 'baz' or 'bar'. returns something very useful.'''
    if foo not in _ALLOWED_ARGS:
        raise ValueError('{foo} wrong, use "baz" or "bar"'.format(foo=repr(foo)))

Create your own error types when apropos

“I want to make an error on purpose, so that it would go into the except”

You can create your own error types, if you want to indicate something specific is wrong with your application, just subclass the appropriate point in the exception hierarchy:

class MyAppLookupError(LookupError):
    '''raise this when there's a lookup error for my app'''

and usage:

if important_key not in resource_dict and not ok_to_be_missing:
    raise MyAppLookupError('resource is missing, and that is not ok.')

回答 1

不要这样做。赤身裸体Exception绝对不是正确的选择。请参阅亚伦·霍尔(Aaron Hall)的出色答案

不能得到比这更多的pythonic:

raise Exception("I know python!")

如果您需要更多信息,请参阅python 的凸起语句文档

DON’T DO THIS. Raising a bare Exception is absolutely not the right thing to do; see Aaron Hall’s excellent answer instead.

Can’t get much more pythonic than this:

raise Exception("I know python!")

See the raise statement docs for python if you’d like more info.


回答 2

在Python3中,有四种用于引发异常的语法:

1. raise exception 
2. raise exception (args) 
3. raise
4. raise exception (args) from original_exception

1.引发异常vs. 2.引发异常(参数)

如果raise exception (args) 用于引发异常,则在 args打印异常对象时将打印出-如下例所示。

  #raise exception (args)
    try:
        raise ValueError("I have raised an Exception")
    except ValueError as exp:
        print ("Error", exp)     # Output -> Error I have raised an Exception 



  #raise execption 
    try:
        raise ValueError
    except ValueError as exp:
        print ("Error", exp)     # Output -> Error 

3.提高

raise不带任何参数的语句重新引发最后一个异常。如果您需要在捕获异常后执行一些操作然后重新引发它,这将很有用。但是,如果以前没有异常,则raise语句引发 TypeErrorException。

def somefunction():
    print("some cleaning")

a=10
b=0 
result=None

try:
    result=a/b
    print(result)

except Exception:            #Output ->
    somefunction()           #some cleaning
    raise                    #Traceback (most recent call last):
                             #File "python", line 8, in <module>
                             #ZeroDivisionError: division by zero

4.从original_exception引发异常(参数)

该语句用于创建异常链接,其中响应另一个异常而引发的异常可以包含原始异常的详细信息-如下例所示。

class MyCustomException(Exception):
pass

a=10
b=0 
reuslt=None
try:
    try:
        result=a/b

    except ZeroDivisionError as exp:
        print("ZeroDivisionError -- ",exp)
        raise MyCustomException("Zero Division ") from exp

except MyCustomException as exp:
        print("MyException",exp)
        print(exp.__cause__)

输出:

ZeroDivisionError --  division by zero
MyException Zero Division 
division by zero

In Python3 there are 4 different syntaxes for rasing exceptions:

1. raise exception 
2. raise exception (args) 
3. raise
4. raise exception (args) from original_exception

1. raise exception vs. 2. raise exception (args)

If you use raise exception (args) to raise an exception then the args will be printed when you print the exception object – as shown in the example below.

  #raise exception (args)
    try:
        raise ValueError("I have raised an Exception")
    except ValueError as exp:
        print ("Error", exp)     # Output -> Error I have raised an Exception 



  #raise execption 
    try:
        raise ValueError
    except ValueError as exp:
        print ("Error", exp)     # Output -> Error 

3.raise

raise statement without any arguments re-raises the last exception. This is useful if you need to perform some actions after catching the exception and then want to re-raise it. But if there was no exception before, raise statement raises TypeError Exception.

def somefunction():
    print("some cleaning")

a=10
b=0 
result=None

try:
    result=a/b
    print(result)

except Exception:            #Output ->
    somefunction()           #some cleaning
    raise                    #Traceback (most recent call last):
                             #File "python", line 8, in <module>
                             #ZeroDivisionError: division by zero

4. raise exception (args) from original_exception

This statement is used to create exception chaining in which an exception that is raised in response to another exception can contain the details of the original exception – as shown in the example below.

class MyCustomException(Exception):
pass

a=10
b=0 
reuslt=None
try:
    try:
        result=a/b

    except ZeroDivisionError as exp:
        print("ZeroDivisionError -- ",exp)
        raise MyCustomException("Zero Division ") from exp

except MyCustomException as exp:
        print("MyException",exp)
        print(exp.__cause__)

Output:

ZeroDivisionError --  division by zero
MyException Zero Division 
division by zero

回答 3

对于常见的情况,您需要针对某些意外情况抛出异常,并且您从不打算抓住它,而只是快速失败以使您能够从那里进行调试(如果发生的话)—最合乎逻辑的是AssertionError

if 0 < distance <= RADIUS:
    #Do something.
elif RADIUS < distance:
    #Do something.
else:
    raise AssertionError("Unexpected value of 'distance'!", distance)

For the common case where you need to throw an exception in response to some unexpected conditions, and that you never intend to catch, but simply to fail fast to enable you to debug from there if it ever happens — the most logical one seems to be AssertionError:

if 0 < distance <= RADIUS:
    #Do something.
elif RADIUS < distance:
    #Do something.
else:
    raise AssertionError("Unexpected value of 'distance'!", distance)

回答 4

首先阅读现有的答案,这只是一个附录。

请注意,可以带或不带参数引发异常。

例:

raise SystemExit

退出程序,但是您可能想知道发生了什么。因此可以使用它。

raise SystemExit("program exited")

这将在关闭程序之前将“程序退出”打印到stderr。

Read the existing answers first, this is just an addendum.

Notice that you can raise exceptions with or without arguments.

Example:

raise SystemExit

exits the program but you might want to know what happened.So you can use this.

raise SystemExit("program exited")

this will print “program exited” to stderr before closing the program.


回答 5

抛出异常的另一种方法是assert。您可以使用assert来验证是否满足条件,否则条件将上升AssertionError。有关更多详细信息,请在此处查看

def avg(marks):
    assert len(marks) != 0,"List is empty."
    return sum(marks)/len(marks)

mark2 = [55,88,78,90,79]
print("Average of mark2:",avg(mark2))

mark1 = []
print("Average of mark1:",avg(mark1))

Another way to throw an exceptions is assert. You can use assert to verify a condition is being fulfilled if not then it will raise AssertionError. For more details have a look here.

def avg(marks):
    assert len(marks) != 0,"List is empty."
    return sum(marks)/len(marks)

mark2 = [55,88,78,90,79]
print("Average of mark2:",avg(mark2))

mark1 = []
print("Average of mark1:",avg(mark1))

回答 6

只是要注意:有时候您确实想处理通用异常。如果要处理大量文件并记录错误,则可能要捕获文件发生的任何错误,将其记录下来,然后继续处理其余文件。在这种情况下,

try:
    foo() 
except Exception as e:
    print(str(e)) # Print out handled error

阻止这样做的好方法。您仍然需要raise特定的异常,以便您了解异常的含义。

Just to note: there are times when you DO want to handle generic exceptions. If you’re processing a bunch of files and logging your errors, you might want to catch any error that occurs for a file, log it, and continue processing the rest of the files. In that case, a

try:
    foo() 
except Exception as e:
    print(str(e)) # Print out handled error

block a good way to do it. You’ll still want to raise specific exceptions so you know what they mean, though.


回答 7

您应该为此学习python的凸起语句。它应该保存在try块中。范例-

try:
    raise TypeError            #remove TypeError by any other error if you want
except TypeError:
    print('TypeError raised')

You should learn the raise statement of python for that. It should be kept inside the try block. Example –

try:
    raise TypeError            #remove TypeError by any other error if you want
except TypeError:
    print('TypeError raised')