Python – catching exceptions (try-except, raise) & logging module (logguru)

1. Common exceptions in Python & amp; catching exceptions

1. Common exceptions

1. NameError: name ‘a’ is not defined
2. IndexError: list index out of range
3.KeyError: ‘nam’
4. ValueError: invalid literal for int() with base 10: ‘b’
5.ZeroDivisionError: division by zero

2. How to analyze and solve these anomalies

1. Analysis of exceptions

1. Check the error message on the console. The error message will display the line number. Click on the file to jump to the problem line.

2. Troubleshoot through debugging. The steps are: breakpoints, single-step debugging, internal debugging of functions, and calculator calculation results. The steps are as follows:

Step over, step out, step into. For details, please refer to: Step into, Step over, Step out. The difference between step into and step over_Diao La Tiao Chuang Tian Ya Blog – CSDN Blog

Where do exceptions generally occur?

Generally, these are areas beyond the control of the developer, such as user input data, user parameters, and function return value calls. Exception capture needs to be added.

2. Catching exceptions

1. Use the try…except statement to passively throw exceptions. The statement formula is as follows:

try:
    Code that may cause exceptions -- it will definitely be executed, and no error will necessarily be reported (user-controlled data + assertion)
except:
    Code that will be executed when an exception occurs. It will not be executed if there is no exception.
except Exception specific type as e:
    Code that will be executed when an exception occurs. It will not be executed if there is no exception.
except Exception as e:-- catch everything
    Code that will be executed when an exception occurs. It will not be executed if there is no exception.
finally:
    The code will be executed whether the exception is caught or not - it is of little significance and does not need to be mastered, as long as you can understand it.

===========The simple thing is as follows: ===============

try:
    Error code
except:
    Processing means and results, including but not limited to: log records, warnings, prompts, etc.
finally:
    It will definitely be executed, regardless of whether the code in try will report an error or not.

================Manually throwing exception==================

raise: Actively throw an exception

Syntactic logic: The mechanism will not affect subsequent code execution due to error reporting

1. Run the code in try first. If an error is reported, the code in except will be executed, and then the subsequent code will be executed.

2. The code in try will not report an error, the statement in except will not be executed, and the subsequent code will be run directly.

Example:

Before using exception catching:

After using exception catching:

2. Use the raise keyword to actively throw an exception. The syntax formula is as follows:

Possibly problematic code
raise ValueError("error prompt") # ValueError is just a kind of error. The specific error type depends on the actual situation.


if a < 0 and b < 0:
    raise ValueError("The input value is less than 0 and does not meet the conditions")

When to use raise?

When developers avoid some exceptions in advance based on business logic, they can actively throw exceptions and terminate the code execution. The purpose is to detect problems earlier and proactively eliminate errors. Here is a simple example:

Extension: In automation scenarios, when do you need to actively throw exceptions?

– Execute the use case and determine whether the execution result is consistent with the expected result. Here, assertions are used. If the assertion fails, the exception is caught and logged.

– Once an exception is caught, the use case is not counted as a failed use case and affects the test report, so exceptions need to be thrown proactively

3. Advanced methods of catching exceptions

Adding except Exception as err after except will save the error information in the err variable, and you can get your own error information. For example:

Error reported before exception is not caught:

Error after using Exception:

In real project situations, different error messages need to be processed differently: recording logs, warnings, sending emails, etc.
– Try to distinguish exceptions and catch them, and use them first
– Finally, add Exception to cover the whole situation

For example:

When a written exception is hit:

When hitting the bottom line logic:

3. Assertion

Definition: Assertion is assert, mainly used to compare actual results with expected results

Type:

– if: Use if conditional judgment to make assertions, using fewer tables

– assert: used more

Result of assertion:

– Success: If the assertion succeeds, there will be no success prompt.

– Failure: If the assertion fails, an exception is thrown, and the code terminates, the test case failure will be displayed in the test report.

– Extension: AssertionError does not display detailed prompt information by default, and notes need to be added manually.

Notice:

If the assertion fails, you need to capture the exception and write it to the log. In addition, after the assertion fails, if the data used by the code is useful, then there is no need to execute the subsequent code~

Write a simple assertion:

str1 = "123hcbhd"
str2 = "cdhvcgdcvkjdf"

try:
    assert len(str1) == len(str2),f"The lengths of the two strings are not equal"
except AssertionError as e:
    logger.error(e)
    raise e

result:
2023-09-15 18:44:48.979 | INFO | __main__:<module>:4 - Logging
2023-09-15 18:44:48.979 | ERROR | __main__:<module>:19 - Assertion failed and judgment error a != b
2023-09-15 18:44:48.980 | ERROR | __main__:<module>:38 - The lengths of the two strings are not equal
Traceback (most recent call last):
  File "E:\python310\py57\day08_Guide package and module and exception handling\log module\log.py", line 39, in <module>
    raise e
  File "E:\python310\py57\day08_Guide package and module and exception handling\log module\log.py", line 36, in <module>
    assert len(str1) == len(str2),f"The lengths of the two strings are not equal"
AssertionError: The lengths of the two strings are not equal

The diagram shows the obvious points:

4. Log processing, use loguru package

Definition: Used to print logs in real time. The usage is as follows:

1. First download the loguru library, which can be downloaded through setting or pip install loguru.

Remarks on the problems I encountered when downloading loguru: the download was never successful, and the python version was inconsistent with the pip version. At this time, you can uninstall python and reinstall it. During the installation, you changed the directory and installed it. Personal test Valid

2. Use loguru to print the log. You can view the following picture:

1. Advanced log usage

You can use the following keywords to increase the visibility and effectiveness of your logs:

  1. sink = file name, directly write it in the current directory to generate the file. After the code is layered, it is placed in the output directory logs. Path processing needs to be done (append mode, the file content can be written continuously and the file name can be easily identified)
  2. encoding: Encoding. There must be Chinese in the log to prevent it from being recognized.
  3. level = “INFO”: must be in uppercase letters. After setting the level, logs of this level and above will be displayed in the file.
  4. rotation: Split files, controlled by time and size, for example: – rotation=”20MB”, -rotation=”1 day”
  5. Retention: The number of log files. If it exceeds the number, old files will be deleted.

Remarks: Log level

Log level:
– TRACE: Nonsense, basically useless
– DEBUG: used for debugging programs, very detailed information about variable values, which has nothing to do with the main business functions and is not available in the online environment.
– INFO: used to record daily information and main business function information
– WARNING: warning message, triggering the edge of error
– ERROR: Something went wrong. Something went wrong. An exception occurred. Assertion failed.
– CRITICAL: Serious error message, crashed, unable to continue running, fatal error

Priority: critical > error > warning > info > debug

Practical exercises:

from loguru import logger

logger.add(
    sink = "my_log",
    encoding="utf8",
    level="INFO",
    rotation="1MB",
    retention=10,
)

# Login case demo
username = input("Please enter username:")
password = input("Please enter password:")

# logger.info(f"The username is: {username}, the password is {password}")

if username == "admin" and password == "123456":
    logger.info("Perform login operation···")
    msg = "Login successful"
    logger.info("Login successful!")
else:
    logger.info("Login operation in progress")
    msg = "Login failed"
    logger.info("Login failed!")

See the screenshot for the result:

You will know it once you read it, and you will lose it once you write it. Just practice~