How to handle exceptions in python conceptually?

python usually defines user-defined exceptions, so they can return a specific user test / output / regardless of when the error occurred in a user-defined class. But I wonder if there is good practice for handling exceptions for a given class in python? In detail, I have the following questions:

  • Should all class-related exceptions be in the file that the python class defines, or should they go to a specific file?

  • Should exceptions be defined for any conceivable case of things that should throw an exception, or is it β€œnormal” to simply define a general exception for the class and print out information about where and what happened in the wrong way by providing some additional text?

  • I would appreciate it if someone could post an example of how a custom exception might / should look like, therefore, to understand why it's nice to define your own specific exception class.

Thanks Alex

+4
source share
1 answer
  • Organizing Python programs at the file level is not particularly interesting, unless you are doing maintenance work. The organization at the module level is much more important because it defines the API (at least at import time), so make sure your exceptions are in the module that uses them.

    A common setting is to export all package exceptions from the root of this package, so you can say from foo import Foo, FooError, BarError . Regardless of whether the definitions can live in one file, you can hide the module system.

  • Depending on how fine-grained you expect to get exceptions. Often, however, I find that the built-in exceptions ( ValueError , TypeError , etc.) are fine-grained enough. For specific things that may go wrong in your package, you can add one or more exceptions.

  • What 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. 
0
source

Source: https://habr.com/ru/post/1441303/


All Articles