Labs / Python OOP

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 27 Python Implementation of Classes and Objects - Implementation of Exception Hierarchy and Custom Exception Classes in Python

Author: Li Zisheng · Source: FreakStudio open documentation · License: CC BY 4.0

Contents
The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 27 Python Implementation of Classes and Objects - Implementation of Exception Hierarchy and Custom Exception Classes in Python

Abstract:

This paper mainly introduces the hierarchy of exceptions when using Python for Object Oriented programming, how to use inheritance relationships to implement custom exception classes in your own projects, and gives an explanation by taking sensor Data Acquisition as an example.

FreakStudio's Blog

Previous Recommendations:

You who study embedded systems still don't know Object Oriented? ?!

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 00 Introduction to Object Oriented Design Methodology

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 01 Basic Concepts of Object Oriented Programming

The Most Beginner-Friendly Object Oriented Programming Tutorial Online: 02 Python Implementation of Classes and Objects - Creating Classes with Python

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 03 Python Implementation of Classes and Objects – Adding Attributes to Custom Classes

The Most Beginner-Friendly Object Oriented Programming Course on the Whole Network: 04 Python Implementation of Classes and Objects – Adding Methods to Custom Classes

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 05 Python Implementation of Classes and Objects - PyCharm Code Tab

The Most Beginner-Friendly Object Oriented Programming Course on the Whole Network: 06 Python Implementation of Classes and Objects - Data Encapsulation of Custom Classes

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 07 Python Implementation of Classes and Objects - Type Annotations

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 08 Python Implementation of Classes and Objects - @property Decorator

The Most Beginner-Friendly Object Oriented Programming Tutorial Across the Network: 09 Python Implementation of Classes and Objects - Relationships Between Classes

The Most Beginner-Friendly Object Oriented Programming Tutorial Across the Network: 10 Python Implementation of Classes and Objects - Class Inheritance and Liskov Substitution Principle

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 11 Python Implementation of Classes and Objects - Subclass Calling Parent Class Methods

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 12 Python Implementation of Classes and Objects - Using Python's logging Module to Output Program Runtime Logs

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 13 Python Implementation of Classes and Objects – Installation and Usage of Sourcetrail, a Fantastic Tool for Visual Code Reading

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 14 Python Implementation of Classes and Objects - Static Methods and Class Methods of Classes

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 15 Python Implementation of Classes and Objects - The __slots__ Magic Method

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 16 Python Implementation of Classes and Objects - Polymorphism, Method Overriding and Open Closed Principle

The most beginner-friendly Object Oriented programming tutorial across the network: 17 Python implementation of classes and objects - duck typing and "file-like object"

The most beginner-friendly Object Oriented programming tutorial across the entire network: 18 Python implementation of classes and objects - multiple inheritance and serial port data curve plotting with PyQtGraph

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 19 Python Implementation of Classes and Objects – Using PyCharm to Automatically Generate File Comments and function Comments

The Most Beginner-Friendly Object Oriented Programming Tutorial Across the Network: 20. Python Implementation of Classes and Objects – Implementation of Composition Relationship and CSV File Saving

The Most Beginner-Friendly Object Oriented Programming Tutorial Across the Network: 21 Python Implementation of Classes and Objects - Multi-File Organization: Module and Package

The Best Entry-Level Object Oriented Programming Tutorial on the Whole Network: 22 Python Implementation of Classes and Objects - Exceptions and Syntax Errors

The Most Beginner-Friendly Object Oriented Programming Tutorial Across the Network: 23 Python Implementation of Classes and Objects - Throwing Exceptions

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 24 Python Implementation of Classes and Objects - Exception Catching and Handling

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 25 Python Implementation of Classes and Objects - Python Determines Input Data Types

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 26 Python Implementation of Classes and Objects - Context Managers and the with Statement

More exciting content is available here:

Speed Up Your Python: A Quick Guide to Python Parallel Computing

Mastering the Debugging Principles of CM3 Microcontrollers in One Article

After half a month of dedicated grinding, the ultimate summary of embedded technology stack is now released

The "Secret Martial Arts Manual" for Computer Science Competitions

Document and Code Acquisition:

You can download the document via the following link:

https://github.com/leezisheng/Doc

19 4 26 5 74

This document mainly introduces how to conduct Object Oriented programming with Python, and it requires readers to have a basic understanding of Python syntax and single-chip microcomputer development. Compared with other blogs or books that explain Python Object Oriented programming, this document is more detailed and focuses on embedded host computer applications. It takes the common serial port data transmission and reception, data processing, dynamic graph drawing and other functions between the host computer and the slave computer as application examples, and uses the Sourcetrail code software to visually read the code to facilitate readers' understanding.

The link to obtain the relevant sample code is as follows:

https://github.com/leezisheng/Python-OOP-Demo

Body Text

Exception Level

Most exceptions are subclasses of the Exception class, but not all exceptions are. The Exception class itself actually inherits from BaseException. In fact, all exceptions must inherit from the BaseException class or its subclasses.

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 27 Python Implementation of Classes and Objects - Implementation of Exception Hierarchy and Custom Exception Classes in Python
The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 27 Python Implementation of Classes and Objects - Implementation of Exception Hierarchy and Custom Exception Classes in Python

There are two key exceptions, SystemExit and KeyboardInterrupt, that inherit directly from BaseException rather than Exception:

The class hierarchy of built-in exceptions is as follows:

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole Network: 27 Python Implementation of Classes and Objects - Implementation of Exception Hierarchy and Custom Exception Classes in Python

When we use only an `except:` clause without specifying any type of exception, it will catch all

A subclass of BaseException; this means it will catch all exceptions, including the two special exception objects mentioned above. If you want to catch all exceptions except SystemExit and KeyboardInterrupt, you should explicitly specify to catch Exception. Furthermore, if you really intend to catch all exceptions, I recommend that you use the except BaseException: syntax instead of except:. This signals to others that you are deliberately doing this to handle special exceptions.

Custom Exception Class

Typically, when we need to trigger an exception in a specific scenario, we may find that there is no existing built-in exception object that meets our needs. Fortunately, however, creating our own exception class is quite straightforward. Exception classes are usually named to convey what kind of error has occurred, and we can also add any required parameters in the initialization function to provide more detailed information.

Whether directly or indirectly, exceptions should all derive from the Exception class. Exception classes can be defined to do anything that other classes can do, but they should generally be kept simple; they usually only provide a few properties to allow the corresponding exception handler to extract information about the error. Most exception names end with "Error", following the naming pattern of standard exceptions.

Here, we define an InvalidIDError to indicate that the incoming sensor ID is invalid.

Meanwhile, in the try block, the except block statement is executed after a user-defined exception occurs, and the variable e is used to create an instance of the InvalidIDError class. The sample code is as follows:

# Define an exception for an illegal ID
class InvalidIDError(Exception):
    pass

class SensorClass(SerialClass):
    # Class variables:
    #   RESPOND_MODE - respond mode - 0
    #   LOOP_MODE    - loop mode - 1
    RESPOND_MODE,LOOP_MODE = (0,1)
    # Class variables:
    #   START_CMD       - start command      -0
    #   STOP_CMD        - stop command      -1
    #   SENDID_CMD      - send ID command    -2
    #   SENDVALUE_CMD   - send data command   -3
    START_CMD,STOP_CMD,SENDID_CMD,SENDVALUE_CMD = (0,1,2,3)

    # Class initialization
    def __init__(self,port:str = "COM11",id:int = 0,state:int = RESPOND_MODE):
        try:
            # Check whether the input port number is of type str
            if type(port) is not str:
                raise TypeError("InvalidPortError:",port)
            # Check whether the ID is between 0 and 99
            if id <= 0 or id >= 99:
                # After an exception is raised, the code after it will not be executed
                # This exception is raised when the type of an argument passed to a function or method is incorrect or the value of the argument is invalid.
                raise InvalidIDError("InvalidIDError:",id)
            # Call the parent class initialization method; the super() function connects the parent class and the child class
            super().__init__(port)
            self.sensorvalue = 0
            self.sensorid    = id
            self.sensorstate = state
            print("Sensor Init")
            logging.info("Sensor Init")
        except TypeError:
            # When an exception occurs, output the following statement to remind the user to re-enter the port number
            print("Input error com, Please try new com number")
        except InvalidIDError as e:
            # When an exception occurs, output the following statement to remind the user to re-enter the ID
            print("Input error ID, Please try id : 0~99")
            print(e.args)

The results of running the code are as follows:

0 99 100

For the InvalidIDError class, we can pass any number of arguments to the exception; typically a string message is used, but any object that may be used for subsequent exception handling is acceptable.

The Exception.__init__ method is designed to accept arbitrary parameters and store them as a tuple in an attribute named args. This makes it easier for us to define new exceptions without needing to override the __init__ method.

Of course, if you need to customize the initialization function, this is a completely feasible approach, and we can do it as follows.

For example, when receiving sensor data, the sensor data may sometimes deviate significantly from the actual value. In the RecvSensorValue method of the MasterClass host class for receiving sensor data, we can design an InvalidSensorValueError exception class, and in the initialization function of this exception class, receive the currently obtained sensor value and the set sensor data threshold as parameters. In addition, it also has a method for calculating the difference between the current sensor value and the set threshold. The sample code is as follows:

# Exception indicating that the sensor data is too high
class InvalidSensorValueError(Exception):
    def __init__(self,recvvalue,setvalue):
        super().__init__("Receive Sensor Value is too high")
        self.recvvalue = recvvalue
        self.setvalue = setvalue
    # Calculate the error between the received data and the set data
    def cal_offset(self):
        offset = self.setvalue - self.recvvalue
        return offset

class MasterClass(SerialClass,PlotClass):
    ...
    # Receive the sensor data
    def RecvSensorValue(self):

        try:
            # Set threshold
            setvalue = 99
            data = super().ReadSerial()

            # If the received sensor data is greater than the threshold
            if data >= setvalue:
                raise InvalidSensorValueError(data,setvalue)

            print("MASTER RECIEVE DATA : " + str(data))
            logging.info("MASTER RECIEVE DATA : " + str(data))
            self.valuequeue.put(data)
        except InvalidSensorValueError as e:
            print("invalid sensor value",e.args)
            print("value offset is : ",e.cal_offset())
        return data 
    ...
if __name__ == "__main__":
    # Create the master class
    m = MasterClass()
    m.StartMaster()
    m.RecvSensorValue()

Run the code, and the results are as follows:

1 V2.6 100

There are many reasons why it is worth considering how to define our own exceptions. Doing so helps add information to exceptions or log them in other forms. However, the real advantage of custom exceptions is that they enable the creation of frameworks, libraries, or APIs for others to use. In this process, we must take care to ensure that the exceptions thrown by the code we write are reasonable for Client programmers. They should be able to handle these exceptions easily and have a clear description of the current situation.At the same time, Client programmers should be able to easily figure out how to fix these errors (if they cause bugs in their code) or handle these exceptions (if it is a situation they need to be aware of). This not only requires us to ensure the clarity and consistency of exception handling, but also to take into account the overall readability and maintainability of the program.

347622978