问题:关于捕获任何异常

我如何编写一个try/ except块来捕获所有异常?

How can I write a try/except block that catches all exceptions?


回答 0

您可以,但您可能不应该:

try:
    do_something()
except:
    print "Caught it!"

但是,这也会捕获类似的异常KeyboardInterrupt,您通常不希望那样,对吗?除非您立即重新引发异常-参见docs中的以下示例:

try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except IOError as (errno, strerror):
    print "I/O error({0}): {1}".format(errno, strerror)
except ValueError:
    print "Could not convert data to an integer."
except:
    print "Unexpected error:", sys.exc_info()[0]
    raise

You can but you probably shouldn’t:

try:
    do_something()
except:
    print "Caught it!"

However, this will also catch exceptions like KeyboardInterrupt and you usually don’t want that, do you? Unless you re-raise the exception right away – see the following example from the docs:

try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except IOError as (errno, strerror):
    print "I/O error({0}): {1}".format(errno, strerror)
except ValueError:
    print "Could not convert data to an integer."
except:
    print "Unexpected error:", sys.exc_info()[0]
    raise

回答 1

除了裸露的except:子句(就像其他人说的那样,您不应该使用),您可以简单地捕获Exception

import traceback
import logging

try:
    whatever()
except Exception as e:
    logging.error(traceback.format_exc())
    # Logs the error appropriately. 

通常,仅当您想在终止之前处理任何其他未捕获的异常时,才通常考虑在代码的最外层执行此操作。

的优势,except Exception在裸露的except是,有少数exceptions,它不会赶上,最明显KeyboardInterruptSystemExit:如果你抓住了,吞下这些,那么你可以让任何人都很难离开你的脚本。

Apart from a bare except: clause (which as others have said you shouldn’t use), you can simply catch Exception:

import traceback
import logging

try:
    whatever()
except Exception as e:
    logging.error(traceback.format_exc())
    # Logs the error appropriately. 

You would normally only ever consider doing this at the outermost level of your code if for example you wanted to handle any otherwise uncaught exceptions before terminating.

The advantage of except Exception over the bare except is that there are a few exceptions that it wont catch, most obviously KeyboardInterrupt and SystemExit: if you caught and swallowed those then you could make it hard for anyone to exit your script.


回答 2

您可以执行此操作以处理一般异常

try:
    a = 2/0
except Exception as e:
    print e.__doc__
    print e.message

You can do this to handle general exceptions

try:
    a = 2/0
except Exception as e:
    print e.__doc__
    print e.message

回答 3

要捕获所有可能的异常,请捕获BaseException。它位于Exception层次结构的顶部:

Python 3:https//docs.python.org/3.5/library/exceptions.html#exception-hierarchy

Python 2.7:https//docs.python.org/2.7/library/exceptions.html#exception-hierarchy

try:
    something()
except BaseException as error:
    print('An exception occurred: {}'.format(error))

但是,正如其他人所提到的那样,通常仅在特定情况下才需要此功能。

To catch all possible exceptions, catch BaseException. It’s on top of the Exception hierarchy:

Python 3: https://docs.python.org/3.5/library/exceptions.html#exception-hierarchy

Python 2.7: https://docs.python.org/2.7/library/exceptions.html#exception-hierarchy

try:
    something()
except BaseException as error:
    print('An exception occurred: {}'.format(error))

But as other people mentioned, you would usually not need this, only for specific cases.


回答 4

非常简单的示例,类似于此处找到的示例:

http://docs.python.org/tutorial/errors.html#defining-clean-up-actions

如果您尝试捕获所有异常,则将所有代码放在“ try:”语句中,代替“ print”执行可能会引发异常的操作。”。

try:
    print "Performing an action which may throw an exception."
except Exception, error:
    print "An exception was thrown!"
    print str(error)
else:
    print "Everything looks great!"
finally:
    print "Finally is called directly after executing the try statement whether an exception is thrown or not."

在上面的示例中,您将按以下顺序查看输出:

1)执行可能会引发异常的动作。

2)无论是否引发异常,在执行try语句后直接调用final。

3)“引发了异常!” 或“一切看起来都很棒!” 取决于是否引发异常。

希望这可以帮助!

Very simple example, similar to the one found here:

http://docs.python.org/tutorial/errors.html#defining-clean-up-actions

If you’re attempting to catch ALL exceptions, then put all your code within the “try:” statement, in place of ‘print “Performing an action which may throw an exception.”‘.

try:
    print "Performing an action which may throw an exception."
except Exception, error:
    print "An exception was thrown!"
    print str(error)
else:
    print "Everything looks great!"
finally:
    print "Finally is called directly after executing the try statement whether an exception is thrown or not."

In the above example, you’d see output in this order:

1) Performing an action which may throw an exception.

2) Finally is called directly after executing the try statement whether an exception is thrown or not.

3) “An exception was thrown!” or “Everything looks great!” depending on whether an exception was thrown.

Hope this helps!


回答 5

有多种方法可以做到这一点,特别是在Python 3.0及更高版本中

方法1

这是简单的方法,但不建议使用,因为您不知道确切的代码行实际引发异常:

def bad_method():
    try:
        sqrt = 0**-1
    except Exception as e:
        print(e)

bad_method()

方法2

建议使用此方法,因为它提供了有关每个异常的更多详细信息。这包括:

  • 您代码的行号
  • 文件名
  • 实际错误更详细

唯一的缺点是需要导入tracback。

import traceback

def bad_method():
    try:
        sqrt = 0**-1
    except Exception:
        print(traceback.print_exc())

bad_method()

There are multiple ways to do this in particular with Python 3.0 and above

Approach 1

This is simple approach but not recommended because you would not know exactly which line of code is actually throwing the exception:

def bad_method():
    try:
        sqrt = 0**-1
    except Exception as e:
        print(e)

bad_method()

Approach 2

This approach is recommended because it provides more detail about each exception. It includes:

  • Line number for your code
  • File name
  • The actual error in more verbose way

The only drawback is tracback needs to be imported.

import traceback

def bad_method():
    try:
        sqrt = 0**-1
    except Exception:
        print(traceback.print_exc())

bad_method()

回答 6

我刚刚发现了这个小技巧,可以测试Python 2.7中的异常名称。有时我已经在代码中处理了特定的异常,因此我需要进行测试以查看该名称是否在已处理的异常列表中。

try:
    raise IndexError #as test error
except Exception as e:
    excepName = type(e).__name__ # returns the name of the exception

I’ve just found out this little trick for testing if exception names in Python 2.7 . Sometimes i have handled specific exceptions in the code, so i needed a test to see if that name is within a list of handled exceptions.

try:
    raise IndexError #as test error
except Exception as e:
    excepName = type(e).__name__ # returns the name of the exception

回答 7

try:
    whatever()
except:
    # this will catch any exception or error

值得一提的是,这不是正确的Python编码。这还将捕获许多您可能不想捕获的错误。

try:
    whatever()
except:
    # this will catch any exception or error

It is worth mentioning this is not proper Python coding. This will catch also many errors you might not want to catch.


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。