[Python Internet of Things]Python Basics and Grammar--Error Handling--Python Quick Start to Develop Internet of Things Host Computer Programs

I. Introduction

        When writing code in Python, you will often encounter errors. These errors may be due to syntax errors, runtime errors, or other reasons. Python provides some built-in tools and techniques to deal with these errors, allowing for better diagnosis and repair of errors as they arise.

2. Common examples

        Here is some sample code and explanations of Python error handling.

        1. SyntaxError

A SyntaxError usually occurs when you use the wrong syntax         in your Python code . For example, the following code has a syntax error because it is missing a colon:

if x == 5
    print("x is equal to 5")

        will result in the following error:

File "example.py", line 1
    if x == 5
            ^
SyntaxError: invalid syntax

        To fix this error, just add a colon at the end of the 'if' statement:

if x == 5:
    print("x is equal to 5")

        2. NameError

Python raises a NameError when you use an undefined variable or function         in your code . For example, the following code raises a NameError because the variable 'y' is undefined:

x = 10
print(y)

        will result in the following error:

Traceback (most recent call last):
  File "example.py", line 2, in <module>
    print(y)
NameError: name 'y' is not defined

        In order to fix this error, you need to define the variable 'y' first:

x = 10
y = 5
print(y)

        3.TypeError

Python raises TypeError when you use incompatible data types         in your code . For example, the following code raises a TypeError because integers cannot be concatenated with strings:

x = 10
print("The value of x is " + x)

        will result in the following error:

Traceback (most recent call last):
  File "example.py", line 2, in <module>
    print("The value of x is " + x)
TypeError: can only concatenate str (not "int") to str

        To fix this error, you need to convert the integer to a string:

x = 10
print("The value of x is " + str(x))

        4. ValueError

        Python raises a ValueError when you use an invalid value in your code. For example, the following code raises ValueError because the 'int' function cannot convert the string "abc" to an integer:

x = int("abc")

        will result in the following error:

Traceback (most recent call last):
  File "example.py", line 1, in <module>
    x = int("abc")
ValueError: invalid literal for int() with base 10: 'abc'

        To fix this error, you need to check before converting the string to an integer:

x_str = "abc"
if x_str.isdigit():
    x = int(x_str)
else:
    print("x_str is not a valid integer")

        5. FileNotFoundError

Python raises FileNotFoundError when         you try to open a file that doesn't exist . For example, the following code will raise FileNotFoundError because the file does not exist (this part will be shared in the next article):

with open("example.txt", "r") as f:
    contents = f.read()

        will result in the following error:

Traceback (most recent call last):
  File "example.py", line 1, in <module>
    with open("example.txt", "r") as f:
FileNotFoundError: [Errno 2] No such file or directory: 'example.txt'

        In order to fix this error, you need to make sure the file exists:

import os.path

filename = "example.txt"
if os.path.exists(filename):
    with open(filename, "r") as f:
        contents = f.read()
else:
    print(f"{filename} does not exist")

        6. ZeroDivisionError

Python raises ZeroDivisionError         when you try to divide another number by 0 . For example, the following code raises ZeroDivisionError:

x = 10 / 0

        will result in the following error:

Traceback (most recent call last):
  File "example.py", line 1, in <module>
    x = 10 / 0
ZeroDivisionError: division by zero

        To fix this error, you need to make sure you don't set the divisor to 0:

x = 10
y = 2
if y != 0:
    z = x / y
    print(z)
else:
    print("y cannot be 0")

        7. try-except

        Besides the above mentioned errors, Python also provides 'try-except' statement to handle other types of errors. The 'try-except' statement tries to execute some code and catches an exception if something goes wrong . Here is a sample code:

try:
    x = int(input("Please enter a number: "))
    y = 10 / x
    print(y)
except ValueError:
    print("Please enter a valid integer.")
except ZeroDivisionError:
    print("Cannot divide by zero.")
except Exception as e:
    print(f"An error occurred: {e}")

        In the code above, we first try to convert the string entered by the user into an integer. If ValueError occurs, an error message is printed. If the divisor is 0, another error message is printed. Finally, we use 'except Exception as e' to handle any other type of error, and print the error message.

        8. traceback

        Python also provides the 'traceback' module to generate detailed error reports. 'traceback' can help you better understand the cause of errors and guide you to fix them. Here is a sample code:

import traceback

def divide(x, y):
    return x / y

try:
    result = divide(10, 0)
except Exception as e:
    print(traceback.format_exc())

        In the above code, we defined a 'divide' function to divide two numbers. We try to call the 'divide' function with 0 as the divisor and use the 'traceback' module to print a detailed error report when an error occurs. Running the above code will produce the following output:

Traceback (most recent call last):
  File "example.py", line 7, in <module>
    result = divide(10, 0)
  File "example.py", line 4, in divide
    return x / y
ZeroDivisionError: division by zero

        In the above output, we can see exactly where and why the error occurred. This will help you better understand and fix errors. (I personally think that this method is rarely used in the development of the Internet of Things)

        9. logging

        Finally, Python also provides the 'logging' module to help you log errors and debug information . With 'logging', you can log any messages you want , including error messages, warning messages, and debug messages . Here is a sample code:

import logging

logging.basicConfig(filename="example.log", level=logging.DEBUG)

def divide(x, y):
    try:
        result = x / y
    except ZeroDivisionError as e:
        logging.error("Cannot divide by zero")
        raise e
    return result

result = divide(10, 0)

        In the above code, we first use the 'basicConfig' method to configure the logger. We specify the log file name and log level. Then, we define a 'divide' function to divide two numbers. If the divisor is 0, we log the error message using the 'logging.error' method. Finally, we call the 'divide' function in the main function.

        Running the above code will generate a log file 'example.log'. The file will contain the following:

ERROR:root:Cannot divide by zero
Traceback (most recent call last):
  File "example.py", line 14, in <module>
    result = divide(10, 0)
  File "example.py", line 9, in divide
    raise e
ZeroDivisionError: division by zero

        In the log file above, we can see the errors and error messages that occurred. This will help you better track and resolve issues. (I personally think that this method is rarely used in the development of the Internet of Things)

3. Key points

        In computer programming, English ability is very important, including but not limited to reading documents and finding errors! So, the best way is to improve your English!

Guess you like

Origin blog.csdn.net/qq_39724355/article/details/130671109