简体   繁体   English

python捕获一些异常

[英]python catch several exceptions

I have some code that is calling several methods from multiple functions. 我有一些代码从多个函数调用多个方法。 Some of these methods may raise an exception. 其中一些方法可能会引发异常。 Each can raise a different type of exception. 每个都可以引发不同类型的异常。 In my main script, I would like to log the exception and then just exit. 在我的主脚本中,我想记录异常然后退出。 So, no matter what the exception type, log it and exit 因此,无论何种异常类型,都将其记录并退出

My question is this: is it better to list all the exceptions that might be generated, or just catch a generic Exception? 我的问题是:列出所有可能生成的异常还是仅捕获一个通用异常更好? Which is more pythonic? 哪个更pythonic?

example: 例:

try:
    some_stuff()
except (Exc1, Exc2, Exc3) as exc:
    loger.exception(exc)

or this: 或这个:

try:
    some_stuff()
except Exception as exc:
    loger.exception(exc)

Your plan to catch exception in main code, log it and terminate is good one. 您计划在主代码中捕获异常,将其记录并终止的计划是一个好方案。

There could be exceptions, which are fine and do not mean, you shall consider them as problem, eg KeyboardInterrupt 可能有一些异常,这很好,并不意味着您应将它们视为问题,例如KeyboardInterrupt

The strategy could be: 该策略可以是:

  • first, catch all the exceptions, which you expect to be fine and pass 首先,捕获所有您希望可以pass的异常
  • then catch general Exception , log it and terminate. 然后捕获一般Exception ,将其记录并终止。

The code could look like: 代码看起来像:

try:
    some(stuff) # ...
# First, resolve expected exceptions
except KeyboardInterrupt:
    pass
# Finally, log unexpected ones
except Exception as exc:
    logger.exception(exc)
    return # time to terminate

When is catching exceptions explicitly a failure 什么时候明确捕获异常失败

The advice to be better by explicitly catching all expected exceptions comes short in case an unexpected exception happens. 如果意外发生异常,则明确建议捕获所有预期异常会更好。 Your plan to catch whatever comes to log file sounds good and provide enough information for resolving the problems later on. 您计划捕获任何日志文件的计划听起来不错,并且为以后解决问题提供了足够的信息。

Imagine, you have a daemon, which shall run and run. 想象一下,您有一个守护程序,它将继续运行。 Under some conditions, it might fail. 在某些情况下,它可能会失败。

With only expecting explicit exception, it may happen, unexpected exception happens, no expect would have a chance to log this to a log file, stacktrace would be printed to stdout and forgotten and program terminates. 仅预期显式异常可能会发生,意外异常会发生,没有expect会有机会将其记录到日志文件,stacktrace将被打印到stdout并被遗忘并且程序终止。

This is clear and very reasonable use case for catching exception generally. 通常,这是捕获异常的明确且非常合理的用例。

From the documentation : 文档中

Because except: catches all exceptions, including SystemExit, KeyboardInterrupt, and GeneratorExit (which is not an error and should not normally be caught by user code), using a bare except: is almost never a good idea. 因为except:裸露的except:几乎绝不是一个好主意,因为它捕获所有异常,包括SystemExit,KeyboardInterrupt和GeneratorExit(这不是错误,通常不应被用户代码捕获)。 In situations where you need to catch all “normal” errors, such as in a framework that runs callbacks, you can catch the base class for all normal exceptions, Exception. 在需要捕获所有“常规”错误的情况下,例如在运行回调的框架中,可以捕获所有常规异常的基类Exception。 Unfortunately in Python 2.x it is 不幸的是在Python 2.x中
possible for third-party code to raise exceptions that do not inherit from Exception, so in Python 2.x there are some cases where you may have to use a bare except: and manually > re-raise the exceptions you don't want to catch. 第三方代码可能会引发不继承自Exception的异常,因此在Python 2.x中,在某些情况下,您可能必须使用裸露的例外:并且手动>重新引发您不希望的异常抓住。

In general, it is better to catch explicit exceptions. 通常,最好捕获显式异常。 In Python 2, how you are doing it can result in exceptions you still don't catch if an external module is throwing something that doesn't inherit exception. 在Python 2中,您的操作方式可能会导致异常,如果外部模块抛出的东西不会继承异常,那么您仍然无法捕获异常。

By catching explicit exceptions you are able to handle errors you know can occur. 通过捕获显式异常,您可以处理可能发生的错误。 If you catch all, your application could do something unexpected and you may handle it incorrectly. 如果全部捕获,则您的应用程序可能会执行意外的操作,并且可能会处理不正确。

Additionally, do you really want to catch someone using Ctrl+C to end your program? 另外,您是否真的想使用Ctrl + C来结束程序?

In all languages, times, and places it is better to specify specific exceptions. 在所有语言,时间和地点,最好指定特定的例外。 That way you won't mask a condition you didn't expect to. 这样,您就不会掩盖意想不到的状况。 NEVER catch Exception in production code unless you have a very, very good reason, or your handler is truly generic. 除非您有非常非常好的理由,或者您的处理程序是真正通用的,否则切勿在生产代码中捕获Exception An example of a suitably generic handler is one which logs, performs cleanup, and reraises. 适当的通用处理程序的一个示例是记录,执行清理和重新评估的处理程序。

Take a note out of Tim Peter's book: 记下蒂姆·彼得的书:

>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
...

Explicit is better than implicit. 显式胜于隐式。 It's more "pythonic" to write out the possible exceptions. 写出可能的异常更为“ pythonic”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM