39

是否有可能在 Python中捕获任何错误?我不在乎具体的例外是什么,因为它们都有相同的后备。

4

8 回答 8

57

单独使用except将捕获任何没有段错误的异常。

try:
    something()
except:
    fallback()

您可能需要单独处理 KeyboardInterrupt 以防您需要使用它来退出脚本:

try:
    something()
except KeyboardInterrupt:
    return
except:
    fallback()

有一个很好的基本例外列表,您可以在此处捕获。我也很喜欢从异常中检索调用堆栈的回溯模块。尝试traceback.format_exc()traceback.print_exc()在异常处理程序中。

于 2011-07-25T14:28:13.227 回答
39
try:
    # do something
except Exception, e:
    # handle it

对于 Python 3.x:

try:
    # do something
except Exception as e:
    # handle it
于 2011-07-25T14:29:17.283 回答
16

您可能还想查看sys.excepthook

当异常被引发但未被捕获时,解释器调用 sys.excepthook 并带有三个参数,异常类、异常实例和回溯对象。在交互式会话中,这发生在控制返回到提示之前;在 Python 程序中,这发生在程序退出之前。可以通过将另一个三参数函数分配给 sys.excepthook 来自定义对此类顶级异常的处理。

例子:

def except_hook(type, value, tback):
    # manage unhandled exception here
    sys.__excepthook__(type, value, tback) # then call the default handler

sys.excepthook = except_hook
于 2011-07-25T18:25:33.840 回答
6

引用赏金文本:

我希望能够捕获任何异常,甚至是奇怪的异常,例如键盘中断甚至系统退出(例如,如果我的 HPC 管理器抛出错误)并获得异常对象 e 的句柄,无论它可能是什么。我想处理 e 并自定义打印,甚至通过电子邮件发送

查看异常层次结构,您需要捕获BaseException

BaseException
 +-- SystemExit
 +-- KeyboardInterrupt
 +-- GeneratorExit
 +-- Exception

这将捕获KeyboardInterrupt,SystemExitGeneratorExit, 它们都继承自BaseException但不继承自Exception, 例如

try:
    raise SystemExit
except BaseException as e:
    print(e.with_traceback)
于 2020-10-01T20:50:07.803 回答
2

不提及您要自己处理的异常类型就可以完成这项工作。

尝试这个:

    try:
       #code in which you expect an exception 
    except:
       #prints the exception occured

如果您想知道发生的异常类型:

    try:
       #code in which you expect an exception 
    except Exception as e:
       print(e)
       #for any exception to be catched

有关详细说明,请参阅此 https://www.tutorialspoint.com/python/python_exceptions.htm

于 2020-10-05T14:45:25.093 回答
1

以下仅对我有用(在 PY2 和 PY3 中):

try:
  # (Anything that produces any kind of error)
except:
  ertype = sys.exc_info()[0]  # E.g. <class 'PermissionError'>
  description = sys.exc_info()[1]   # E.g. [Errno 13] Permission denied: ...
  # (Handle as needed ) 
于 2020-08-21T08:47:40.657 回答
0

Python 中的内置异常

内置异常类分为定义错误类的基本错误类和定义您更可能不时看到的异常的具体错误类。

关于内置异常的更详细文档可以在 [https://docs.python.org/3/library/exceptions.html] 中找到

自定义例外

它用于适合您的特定应用情况。例如,您可以将自己的异常创建为 RecipeNotValidError,因为该食谱在您的类中对开发烹饪应用程序无效。

执行


class RecipeNotValidError(Exception):    
    def __init__(self):       
        self.message = "Your recipe is not valid"        
        try:            
            raise RecipeNotValidError
        except RecipeNotValidError as e:            
            print(e.message)

这些是标准库中未定义的自定义异常。您可以按照以下步骤创建自定义类:

  1. 子类化异常类。
  2. 创建您选择的新异常类。
  3. 编写您的代码并使用 try...except 流来捕获和处理您的自定义异常。
于 2020-10-06T11:36:35.297 回答
0
# in python 3

# if you want the error
try:
    func()
except Exception as e:
    exceptionFunc(e)

# if you simply want to know an error occurs
try:
    func()
except:
    exceptionFunc()

# if you don't even wanna do anything
try:
    func()
except:
    pass
于 2020-10-06T11:17:31.100 回答