简体   繁体   English

如何在概念上处理python中的异常?

[英]How to handle exceptions in python conceptually?

in python it is common to define user-defined exceptions so they can return some user-defined test/output/whatever when an error happened in a user-defined class. 在python中,通常定义用户定义的异常,以便在用户定义的类中发生错误时,它们可以返回一些用户定义的测试/输出。 But I wonder, if there is a good practice to handle exceptions for a given class in python? 但我想知道,如果有一个很好的做法来处理python中给定类的异常? In detail, I have the following questions: 详细地说,我有以下问题:

  1. Should all the class-related exceptions go into the file that defines the python class, or should they go into a specific file? 是否所有与类相关的异常都会进入定义python类的文件中,还是应该进入特定的文件?

  2. Should exceptions be defined for any conceivable case of things that should rise an exception, or is it 'ok' to just define a general exception for a class and to print out details of where and what happened in the wrong way by giving some additional text? 是否应该为任何应该引发异常的事物的可能情况定义异常,或者仅仅为类定义一般异常并通过提供一些额外的文本打印出错误方式发生的位置和内容的详细信息“ok” ?

  3. I would appreciate if someone could post an example of how a user-defined exception could/should look like, so to see the reason why it is a good thing to define your own specific exception class. 如果有人可以发布一个用户定义的异常如何/应该是什么样子的示例,我将不胜感激,因此要查看为什么定义您自己的特定异常类是一件好事。

Thanks Alex 谢谢Alex

  1. File-level organisation of Python programs isn't particularly interesting, except when you're doing maintenance. 除了正在进行维护之外,Python程序的文件级组织并不是特别有趣。 The module-level organisation is much more important as it determines the API (at least at import time), so make sure your exceptions are in the module that uses them. 模块级组织在确定API时更为重要(至少在import时),因此请确保您的异常位于使用它们的模块中。

    A common setup is to export all the exceptions of a package from the root of that package, so you can say from foo import Foo, FooError, BarError . 一个常见的设置是从该包的根目录导出包的所有异常,因此您可以from foo import Foo, FooError, BarError Whether the definitions live in the same file can be hidden by the module system. 模块系统是否可以隐藏定义是否存在于同一文件中。

  2. Depends entirely on how fine-grained you expect to catch the exceptions. 完全取决于您期望捕获异常的细粒度。 Often, though, I find that the built-in exceptions ( ValueError , TypeError , etc.) are fine-grained enough. 但是,我经常发现内置的异常( ValueErrorTypeError等)足够精细。 For specific things that might go wrong in your package, you might add one or several exceptions. 对于包中可能出错的特定事物,您可能会添加一个或多个例外。

  3. How's about... 怎么样......

     class ParseError(Exception): def __init__(self, parser_input, line, column): self.input = parse_input self.line = line self.column = column def __str__(self): # format the exception message, showing the offending part of # self.input and what the parser was expecting. 

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

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