简体   繁体   中英

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. But I wonder, if there is a good practice to handle exceptions for a given class in 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?

  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?

  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

  1. File-level organisation of Python programs isn't particularly interesting, except when you're doing maintenance. 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.

    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 . 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. 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. 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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