Location>code7788 >text

The best introductory object-oriented programming tutorials on the web: 27 Python implementation of classes and objects - Exception hierarchy and custom exception class implementation in Python

Popularity:182 ℃/2024-07-30 00:56:22

The best introductory object-oriented programming tutorials on the web: 27 Python implementations of classes and objects - Exception Hierarchy and Custom Exception Class Implementation in Python

image

Abstracts:

This article introduces the hierarchy of exceptions and how to use inheritance relationships to complete the customization of exception classes in their own projects when using Python for object-oriented programming, and explains sensor data collection as an example.

Link to original article:

FreakStudio's Blog

Past Recommendations:

You're learning embedded and you don't know how to be object oriented?

The Best Object-Oriented Programming Tutorials on the Web for Getting Started: 00 Introduction to Object-Oriented Design Methods

The network's most suitable for the introduction of object-oriented programming tutorials: 01 Basic Concepts of Object-Oriented Programming

The Best Object-Oriented Programming Tutorials for Getting Started on the Web: 02 Python Implementations of Classes and Objects - Creating Classes with Python

The Best Object-Oriented Programming Tutorials for Getting Started on the Web: 03 Python Implementations of Classes and Objects - Adding Attributes to Custom Classes

The Best Object-Oriented Programming Tutorial on the Net for Getting Started: 04 Python Implementation of Classes and Objects - Adding Methods to Custom Classes

The Best Object-Oriented Programming Tutorial on the Net for Getting Started: 05 Python Implementation of Classes and Objects - PyCharm Code Tags

The best object-oriented programming tutorials on the net for getting started: 06 Python implementation of classes and objects - data encapsulation of custom classes

The best object-oriented programming tutorial on the net for getting started: 07 Python implementation of classes and objects - type annotations

The best object-oriented programming tutorials on the net for getting started: 08 Python implementations of classes and objects - @property decorator

The best object-oriented programming tutorials on the net for getting started: 09 Python implementation of classes and objects - the relationship between classes

The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 10 Python Implementations of Classes and Objects - Class Inheritance and Richter's Replacement Principle

The best object-oriented programming tutorials on the net for getting started: 11 Python implementation of classes and objects - subclasses call parent class methods

The network's most suitable for the introduction of object-oriented programming tutorials: 12 classes and objects of the Python implementation - Python using the logging module to output the program running logs

The network's most suitable for the introduction of object-oriented programming tutorials: 13 classes and objects of the Python implementation - visual reading code artifacts Sourcetrail's installation use

The Best Object-Oriented Programming Tutorials on the Web for Getting Started: The Best Object-Oriented Programming Tutorials on the Web for Getting Started: 14 Python Implementations of Classes and Objects - Static Methods and Class Methods for Classes

The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 15 Python Implementations of Classes and Objects - __slots__ Magic Methods

The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 16 Python Implementations of Classes and Objects - Polymorphism, Method Overriding, and the Principle of Open-Close

The Best Object-Oriented Programming Tutorials for Getting Started on the Web: 17 Python Implementations of Classes and Objects - Duck Types and "file-like objects"

The network's most suitable for the introduction of object-oriented programming tutorials: 18 classes and objects Python implementation - multiple inheritance and PyQtGraph serial data plotting graphs

The Best Object-Oriented Programming Tutorials on the Web for Getting Started: 19 Python Implementations of Classes and Objects - Using PyCharm to Automatically Generate File Annotations and Function Annotations

The best object-oriented programming tutorials on the net for getting started: 20 Python implementation of classes and objects - Combinatorial relationship implementation with CSV file saving

The best introductory object-oriented programming tutorials on the net: 21 Python implementation of classes and objects - Organization of multiple files: modulemodule and packagepackage

The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 22 Python Implementations of Classes and Objects - Exceptions and Syntax Errors

The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 23 Python Implementation of Classes and Objects - Throwing Exceptions

The Best Object-Oriented Programming Tutorials on the Web for Getting Started: 24 Python Implementations of Classes and Objects - Exception Catching and Handling

The best object-oriented programming tutorials on the web for getting started: 25 Python implementation of classes and objects - Python to determine the type of input data

The Best Object-Oriented Programming Tutorials on the Net for Getting Started: 26 Python Implementations of Classes and Objects - Context Managers and with Statements

More highlights to watch:

Accelerating Your Python: A Quick Guide to Python Parallel Computing

Understanding CM3 MCU Debugging Principles in One Article

Liver half a month, embedded technology stack summary out of the big

The "Secrets of the Martial Arts" of the Computer Competition

A MicroPython open source project collection: awesome-micropython, including all aspects of Micropython tool library

Documentation and code acquisition:

The following link can be accessed to download the document:

/leezisheng/Doc

image

This document mainly introduces how to use Python for object-oriented programming, which requires readers to have a basic understanding of Python syntax and microcontroller 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, with common serial port data sending and receiving, data processing, and dynamic graph drawing as application examples for the host computer and the lower computer, and using Sourcetrail code software to visualize and read the code for readers' easy understanding.

The link to get the relevant sample code is below:/leezisheng/Python-OOP-Demo

main body (of a book)

anomaly cascade

Most exceptions are subclasses of the Exception class, but not all. the Exception class itself actually inherits from BaseException. in fact, all exceptions must inherit from the Base Exception class or a subclass of it.

image

image

There are two key exceptions, SystemExit and KeyboardInterrupt, which inherit directly from BaseException instead of Exception:

  • SystemExit exceptions are thrown when a program exits naturally, usually because a function has been called somewhere in the code (for example, when the user selects the Exit menu option, or clicks the Close button in a window, or enters a command to shut down the server).This exception is designed to complete the cleanup before the program finally exits without explicitly handling it (since the cleanup code occurs in the finally statement).
  • The KeyboardInterrupt exception is common in command-line programs. This exception is thrown when the user interrupts a program by executing a system-dependent key combination (usually Ctrl+C). This is a standard way for the user to intentionally interrupt a running program, and like SystemExit, it should be responded to by ending the program. Also, similar to SystemExit, handling it should be cleaned up in a finally block.

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

image

When we just use the except: clause without adding any type of exception, it will catch all of the

subclass of BaseException; that is, 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 that Exception is caught, and furthermore, if you really want to catch all exceptions, I recommend that you use the except BaseException: syntax instead of except:. This tells others that you are doing this on purpose to handle special exceptions.

Customized Exception Classes

Often, when we need to trigger an exception in a particular situation, we may find that there is no built-in exception object that can meet our needs. Thankfully, however, it is fairly easy to create our own exception classes. The naming of the exception class is usually intended to communicate what kind of error occurred, and we can also add any desired parameters to the initialization function to provide more detailed information.

Whether in a direct or indirect way, exceptions should be derived from the Exception class. The Exception class can be defined to do anything that any other class can do, but it should usually be kept simple, and it often provides only a few properties that allow the appropriate exception handler to extract information about the error. Most exception naming ends with "Error", similar to the naming of standard exceptions.

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

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

_# Define an exception with an illegal ID number_.
class InvalidIDError(Exception).
    pass

class SensorClass(SerialClass).
    _# Class variables: _
    _# RESPOND_MODE -Response mode-0_.
    _# LOOP_MODE - Loop Mode -1_.
    RESPOND_MODE,LOOP_MODE = (0,1)
    _# Class variables: _
    _# START_CMD - Start command -0_
    _# STOP_CMD - shutdown 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)

    _# Initialization of class _
    def __init__(self,port:str = "COM11",id:int = 0,state:int = RESPOND_MODE).
        try.
            _# Determine if input port number is type str _
            if type(port) is not str.
                raise TypeError("InvalidPortError:",port)
            _# Determine if id number is between 0 and 99_.
            if id <= 0 or id >= 99.
                _# When the exception is triggered, the code that follows will not be executed.
                _# This exception is raised when an incorrect type of parameter is passed to a function or method or when the value of a parameter is not legal. _
                raise InvalidIDError("InvalidIDError:",id)
            _# Call the initialization method of the parent class, the super() function connects the parent class to the child class _
            super(). __init__(port)
             = 0
                = id
             = state
            print("Sensor Init")
            ("Sensor Init")
        except TypeError: _# When an exception occurs, the following statement is output to remind the user to re-enter the port number
            _# When an exception occurs, the following statement is output 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 number _
            print("Input error ID, Please try id : 0~99")
            print()

The result of running the code is as follows:

image

For the InvalidIDError class, theWe can pass any number of parameters to the exception, usually with a string message, but any object that might be used for later exception handling is fine.

The Exception.__init__ method is designed to take arbitrary arguments and store them as a tuple in a property called args. This makes it easier to define new exceptions without having to rewrite the init method.

Of course, if a custom initialization function is needed, which is perfectly feasible to do, we can do that.

For example, in receiving sensor data, sometimes the sensor data will deviate too much from the actual data. We can design an InvalidSensorValueError exception class in the RecvSensorValue method of the MasterClass host class to receive the currently acquired sensor value and the set sensor data threshold as parameters in the initialization function of this exception class. In addition, it has a method for calculating the difference between the sensor value and the set threshold this time. The sample code is as follows:

_# Indicates an abnormally high sensor data_
class InvalidSensorValueError(Exception):
    def __init__(self,recvvalue,setvalue):
        super().__init__("Receive Sensor Value is too high")
         = recvvalue
         = setvalue
    _# Calculation of the error value between the received data and the set data_
    def cal_offset(self):
        offset = -
        return offset

class MasterClass(SerialClass,PlotClass):
    ...
    _# Receive sensor data_
    def RecvSensorValue(self):

        try:
            _# Set thresholds_
            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))
            ("MASTER RECIEVE DATA : " + str(data))
            (data)
        except InvalidSensorValueError as e:
            print("invalid sensor value",)
            print("value offset is : ",e.cal_offset())
        return data
    ...
if __name__ == "__main__":
    _# Creating Host Classes_
    m = MasterClass()
    ()
    ()

Run the code with the following results:

image

There are many reasons to consider how we define our exceptions.Doing so helps to add information to the exception or log it in some other form. However, the real advantage of custom exceptions is that they enable the creation of frameworks, libraries, or APIs for others to use.In doing so, we must take care to ensure that the exceptions thrown by the code we write make sense to the client programmer. They should be able to easily handle these exceptions and clearly describe the current situation. At the same time, client programmers should be able to easily see how to fix these errors (if this causes an error in their code) or handle these exceptions (if it is a situation they need to understand). This not only requires us to ensure clarity and consistency in exception handling, but also the overall readability and maintainability of the program.

image