在 Python 中仅捕获一些运行时错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/825909/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 20:55:17  来源:igfitidea点击:

Catch only some runtime errors in Python

pythonexception-handlingtry-catchruntime-error

提问by lfaraone

I'm importing a module which raises the following error in some conditions: RuntimeError: pyparted requires root access

我正在导入一个在某些情况下会引发以下错误的模块:RuntimeError: pyparted requires root access

I know that I can just check for root access before the import, but I'd like to know how to catch this spesific kind of error via a try/except statement for future reference. Is there any way to differentiate between this RuntimeError and others that might be raised?

我知道我可以在导入之前检查 root 访问权限,但我想知道如何通过 try/except 语句捕获这种特定类型的错误以供将来参考。有没有办法区分这个 RuntimeError 和其他可能引发的错误?

回答by gimel

You can check attributes of the exception to differentiate from other possible RuntimeErrorexceptions. For example, re-raise the error if it does not match a predefined message text.

您可以检查异常的属性以区别于其他可能的RuntimeError异常。例如,如果错误与预定义的消息文本不匹配,则重新引发错误。

    try:
        import pypatred
    except RuntimeError,e:
        if e.message == 'RuntimeError: pyparted requires root access':
            return 'pyparted - no root access'
        raise

Of course, direct text comparison is just an example, you could search for included substrings or regular expressions.

当然,直接文本比较只是一个例子,您可以搜索包含的子字符串或正则表达式。

It is worth noting that the .messageattribute of exceptions is deprecated starting with Python 2.6. You can find the text in .args, usually args[0].

值得注意的是,从 Python 2.6 开始不推荐使用.message异常属性。您通常可以在 中找到文本。.argsargs[0]

... For 2.6, the messageattribute is being deprecated in favor of the argsattribute.

... 对于 2.6,该message属性已被弃用,以支持该args属性。

回答by decitrig

I know that I can just check for root access before the import, but I'd like to know how to catch this spesific kind of error via a try/except statement for future reference. Is there any way to differentiate between this RuntimeError and others that might be raised?

我知道我可以在导入之前检查 root 访问权限,但我想知道如何通过 try/except 语句捕获这种特定类型的错误以供将来参考。有没有办法区分这个 RuntimeError 和其他可能引发的错误?

If the error is caused by a specific condition, then I think the easiest way to catch the error is to test for the condition, and you can raise a more specific error yourself. After all the 'error' exists before the error is thrown, since in this case its a problem with the environment.

如果错误是由特定条件引起的,那么我认为捕获错误的最简单方法是测试条件,您可以自己提出更具体的错误。毕竟在抛出错误之前存在“错误”,因为在这种情况下它是环境问题。

I agree with those above - text matching on an error is kind of a terrifying prospect.

我同意上述观点 - 错误的文本匹配是一种可怕的前景。

回答by SilentGhost

try:
    import pyparted
except RuntimeError:
    print('RuntimeError is raised')
    raise

more on exception handling in tutorial.

教程中更多关于异常处理的信息

This situation should produce ImportErrorin my opinion. And you can do it yourself:

这种情况ImportError在我看来应该产生。你可以自己做:

try:
    import pyparted
except RuntimeError as e:
    raise ImportError(e)

回答by 0x6adb015

Yes.

是的。

   try:
        import module
   except RuntimeError:
         pass

imports are interpreted as any other statement, they are not special. You could do an

导入被解释为任何其他语句,它们并不特殊。你可以做一个

if condition:
     import module

回答by Nadia Alramli

try:
   import ...
except RuntimeError:
   # Do something

回答by neotam

RuntimeErrorRaised when an error is detected that doesn't fall in any of the other categories

RuntimeError当检测到不属于任何其他类别的错误时引发

def foo():
   try:
      foo()
   except RuntimeError, e:
      print e
      print " Runtime Error occurred due to exceeded maximum recursion depth "

That is how we will catch the RuntimeError caused by the exceeded recursion limit in python

这就是我们如何在python中捕获由超出递归限制引起的RuntimeError

And if you want to call your function over the recursion limit you can do the following

如果您想通过递归限制调用您的函数,您可以执行以下操作

import sys
def foo():
     try:
        foo()
     except RuntimeError, e:
        sys.setrecursionlimit(1200)
        foo()

But always it is highly not recommended to change the recursion limit, but very small changes in the recursion limit are allowed

但始终强烈不建议更改递归限制,但允许对递归限制进行非常小的更改