Labs / Python OOP

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

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

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

Abstract:

This paper mainly introduces the application scenarios of throwing exceptions, the usage method of the raise statement and the syntax format of the raise statement when using Python Object Oriented programming, and provides corresponding examples to assist the explanation.

FreakStudio's Blog

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 Across the Web: 08 Python Implementation of Classes and Objects - @property Decorator

The Most Beginner-Friendly Object Oriented Programming Tutorial on the Whole 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 across the network: 15 Python implementation of classes and objects - the __slots__ magic method

The Most Beginner-Friendly Object Oriented Programming Tutorial Across the 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 entire 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

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

This document mainly introduces how to use Python for Object Oriented programming, and 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, taking the common serial port data transmission and reception, data processing, dynamic graph drawing of host computer and slave computer as application examples, and uses Sourcetrail code software for visual code reading to facilitate readers' understanding.

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

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

Body Text

In practical programming scenarios, most methods and constructors impose certain restrictions on the passed parameter values; for example, common index values must be non-negative, and object references cannot be null. You should enforce entry parameter checks at the very beginning of a method, and if an invalid value is input, we can use the raise statement to trigger an exception on our own.

The syntax format of raise is as follows:

raise [Exception [, args [, traceback]]]

In the statement, Exception refers to the exception type (e. g., NameError), which can be any one of the standard exceptions; args denotes the user-provided exception parameters. The last parameter is optional (and rarely used in practice), and if present, it is the traceback exception object.

For example, when creating the SensorClass sensor class, we need to restrict the sensor ID to be between 0 and 99; if this condition is not met, an InvalidIDError exception will be thrown. The sample code is as follows:

class SensorClass(SerialClass):
    ...
    # Class initialization
    def __init__(self,port:str = "COM11",id:int = 0,state:int = RESPOND_MODE):
        if id <= 0 or id >= 99:
            # After an exception is raised, the code after it will not be executed
            raise Exception("InvalidIDError:", id)
        ...
if __name__ == "__main__":
    # Create a sensor class with ID 100
    s = SensorClass(port  = "COM11",
                    id      = 100,
                    state = SensorClass.RESPOND_MODE
                    )

The code execution result is as follows:

100 40 1

When an exception is thrown, it appears that the execution of the program stops immediately. All code after the exception throw will not be executed, and unless the exception is handled, the program will exit with an error message. Furthermore, if one function calls another function that throws an exception, all code in the former function after the position where the latter is called will also not be executed. Throwing an exception halts all execution in the function call stack, either being handled properly or causing the interpreter to exit forcibly.

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