简体   繁体   English

在 Python 中引发异常时如何停止程序?

[英]How do I stop a program when an exception is raised in Python?

I need to stop my program when an exception is raised in Python.当 Python 中出现异常时,我需要停止我的程序。 How do I implement this?我该如何实施?

import sys

try:
  print("stuff")
except:
  sys.exit(1) # exiing with a non zero value is better for returning from an error

You can stop catching the exception, or - if you need to catch it (to do some custom handling), you can re-raise:您可以停止捕获异常,或者 - 如果您需要捕获它(进行一些自定义处理),您可以重新引发:

try:
  doSomeEvilThing()
except Exception, e:
  handleException(e)
  raise

Note that typing raise without passing an exception object causes the original traceback to be preserved.请注意,在不传递异常对象的情况下键入raise会导致保留原始回溯。 Typically it is much better than raise e .通常它比raise e好得多。

Of course - you can also explicitly call当然 - 您也可以显式调用

import sys 
sys.exit(exitCodeYouFindAppropriate)

This causes SystemExit exception to be raised, and (unless you catch it somewhere) terminates your application with specified exit code.这会导致引发 SystemExit 异常,并且(除非您在某处捕获它)使用指定的退出代码终止您的应用程序。

If you don't handle an exception, it will propagate up the call stack up to the interpreter, which will then display a traceback and exit.如果您不处理异常,它会将调用堆栈向上传播到解释器,然后解释器将显示回溯并退出。 IOW : you don't have to do anything to make your script exit when an exception happens. IOW :您无需执行任何操作即可在发生异常时退出脚本。

import sys

try:
    import feedparser
except:
    print "Error: Cannot import feedparser.\n" 
    sys.exit(1)

Here we're exiting with a status code of 1. It is usually also helpful to output an error message, write to a log, and clean up.这里我们以状态码 1 退出。输出错误消息、写入日志和清理通常也很有帮助。

据我所知,如果您的脚本没有捕获异常,它将被中断。

import sys

try: 
    # your code here
except Exception as err:
    print("Error: " + str(err))
sys.exit(50) # whatever non zero exit code

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

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