Location>code7788 >text

The best introductory object-oriented programming tutorials on the net: 24 Python implementation of classes and objects - exception catching and handling: try/except statements, file read and write examples, Exception reference

Popularity:113 ℃/2024-07-25 00:55:13

The best introductory object-oriented programming tutorials on the net: 24 Python implementation of classes and objects - exception catching and handling: try/except statements, file read and write examples, Exception reference

image

Abstracts:

This article describes how to use Python object-oriented programming, how to use the try/except statement to catch and handle exceptions, and supplemented with CSV file reading and writing as an example to explain, but also explains how to refer to the Exception object.

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 web for getting started: 20 Python implementation of classes and objects - Combinatorial relationship implementation and 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

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)

When an exception occurs in a Python script, we need to catch it or the program will terminate. To catch an exception, you use the try/except statement, which detects an error in the try block and allows the except statement to catch the exception and handle it.

If you don't want your program to end when an exception occurs, just catch it in a try. Here's a simple try... .except... . else syntax:

try.
<statement>.
except <name>:
< statement> except <name>.

The try statement works as follows:

  • (1) First, execute the try clause (the (multi-line) statement between the try and except keywords).

  • (2) If no exception is raised, the except clause is skipped and the try statement is executed.

  • (3) If an exception occurs during execution of the try clause, the remainder of the clause is skipped. If the type of the exception matches the exception specified after the except keyword, the except clause is executed and execution continues after the try/except block.

  • (4) If an exception occurs that does not match the exception specified in the except clause, it is passed to the outer try statement; if no handle is found, it is an unhandled exception and execution stops with an error message.

The sample code is as follows:

class SensorClass(SerialClass).
    ...
    _# Initialization of class _
    def __init__(self,port:str = "COM11",id:int = 0,state:int = RESPOND_MODE): ...
        try.
            if id <= 0 or id >= 99.
                _# When the exception is triggered, the code that follows will not be executed.
                raise Exception("InvalidIDError:", id)
            _# Call the initialization method of the parent class, the super() function connects the parent class with the child class _
            super(). __init__(port)
             = 0
                = id
             = state
            print("Sensor Init")
            ("Sensor Init")
        except.
            _# 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")
         ...
if __name__ == "__main__".
    _# Create SensorClass with ID number 100_.
    s = SensorClass(port = "COM11",id = 100,state = SensorClass.RESPOND_MODE)

The following is the result of the run:

image

The above way try-except statement catches all the exceptions that occur. But this is not a good way, we can't identify the specific exception information through this program. Because it catches all exceptions.

You can also use the same except statement for multiple exception messages, as shown below:

try.
    Normal operation
   ......................
except(Exception1[, Exception2[,..... .ExceptionN]]).
   If one of the above exceptions occurs, execute this piece of code
   ......................
else.
    If there are no exceptions, execute this code

The try statement can have multiple except clauses to specify handlers for different exceptions.However, at most one handler will be executed. A handler handles exceptions that occur in the corresponding try clause, not in other handlers within the same try statement.The except clause can specify multiple exceptions using a tuple with parentheses, e.g..

... except (RuntimeError, TypeError, NameError):
...     pass

As shown in the example code below, in the initialization method of the SensorClass sensor class, we add a check on the data type of the input port number, and if it is not of str type, then a TypeError exception is thrown:

def __init__(self,port:str = "COM11",id:int = 0,state:int = RESPOND_MODE).
        try.
            _# Determine if the input port number is of 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 ValueError("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 ValueError: _# When an exception occurs, the following statement is output
            _# When an exception occurs, output the following statement to remind the user to re-enter the ID number _# print("Input error com, Please try new com number")
            print("Input error ID, Please try id : 0~99")

The following is the result of the run, you can see that only exceptions with the input error port type are caught and handled, but not exceptions with the ID number of the input error range:

image

In addition to using except blocks to handle exceptions, we can also use finally blocks to perform some necessary cleanup. The code in the finally block is executed regardless of the exception. This is useful if you need to perform a specific task after the code has finished executing (even if an exception was thrown). Some common examples include: clearing an open database connection; closing an open file; sending a close handshake to the network.The finally statement is also important for executing the return statement in our try. the code in finally will still be executed before the return value.

For example, in the FileIOClass class, you need to read and write a csc file. The basic process is to open a csc file, then read it, write it, and finally close the file object. This is a set of conventional process, if I want to catch exceptions in the code process, but also to ensure that no matter whether there is an exception or not, the file must be closed in the end. This time on the use of finally, sample code is as follows:

class FileIOClass.
    def __init__(self,path:str="G:\\\Python Object-Oriented Programming\\\Demo\\")::.
        '''
        Initialize the csv file and column headers
        :param path: file path and filename
        '''
           = path
        try.
            _# path is the output path and filename, newline='' is for no blank lines _
             = open(path, "w+", newline='')
            _# rowname is the column name, index-index, data-data_
             = ['index', 'data']
            _# return a writer object that converts the user's data on the given file-type object to a delimited string _
             = ()
            _# Write the column headings of the csv file _
            ()
        except (FileNotFoundError, IOError):
            print("Could not open file")
            ("Could not open file")
        except KeyboardInterrupt: print("Cancell the file operation")
            print("Cancell the file operation")
            ("Cancell the file operation")
        finally.
                ()

We change the file path to a path that doesn't even exist, initialize the FileIOClass instance object.

The code is as follows:

f = FileIOClass(path = "H:\\/Python Object-Oriented Programming\\Demo\\\")

You can see that the statement in except was run when the IOError occurred:

image

In line 16:

16        except (FileNotFoundError, IOError):

Indicates that this code will be executed whenever either FileNotFoundError or IOError occurs.

In fact, we can handle two or more different exceptions at once with the same code. The specific format is as follows:

except(Exception1[, Exception2[, ... .ExceptionN]])::
   _# One of the above multiple exceptions occurs, execute this block of code_.

When multiple exceptions occur at the same time, we can use the following to print out the class name of the corresponding exception:

except (FileNotFoundError, IOError) as e:
            print("Could not open file",e.__class__.__name__)
            ("Could not open file")

Let's run the code again:

image

Sometimes we need to use a reference to an Exception object when we catch an exception. This usually happens when we define our own exception with specific parameters, in which case we can use the as statement with parameters, as the output of the exception information parameters. The example code is as follows:

except (FileNotFoundError, IOError) as e:
            print("Could not open file",e.__class__.__name__)
            print("The exception arguments were", )
            ("Could not open file")

The result is as follows, you can see that the output parameter in the example is an error code (2), indicating that there is no such file or directory.

image

In fact the exception value received by the variable is usually included in the statement of the exception. In a tuple form variables can receive one or more values. Tuples usually contain error strings, error numbers, and error locations.

image