Today is the 13/100 day of continuous writing. If you have ideas or techniques you’d like to share, feel free to leave them in the comments section.

This article focuses on program error and exception handling, with a brief introduction to the built-in logging module.

Completed articles

  • 1. This is the right way to start learning Python
  • 2. Learn data types and input and output functions without barriers, and snowball into Python
  • 3. No programming without twists, learn Python by snowballing
  • 4. Learn Python halfway through the list
  • 5. The nature of Python loops is that a piece of code is too lazy to repeat itself
  • 6. Python tuples, immutable lists, snowball learning Python
  • Sing sing sing sing Sing Sing Sing Sing Sing Sing Sing Sing Sing Sing Will be. The Python dictionary has been mastered
  • 8. Learn Python from everyday Python
  • 9. On the first hill of the Python learning process, 99% of the people fall down the hill
  • 10. A technical point that’s harder than finding a girlfriend. Python is object-oriented
  • 11. Use code written by someone else, do my work, and spend the rest of the day fishing

This series of articles will be completed before the Spring Festival of 2021, welcome to follow, like, comment -- dream eraser

Python program exception handling and Logging module

13.1 Program Exception

Program exception, is the program goes wrong, programmer commonly called BUG (myna), write a program without error is impossible to happen, and the thing programmers have to do is timely capture errors, modify errors.

13.1.1 Most common error – divisor is 0

A similar problem exists in mathematics, where divisor cannot be zero. The same concept exists in programming.

num1 = 20
num2 = 0
num3 = num1 / num2
print(num3)
Copy the code

The following error occurs when running the code:

Traceback (most recent call last):
  File "D:/gun/2/demo7.py", line 3, in <module>
    num3 = num1 / num2
ZeroDivisionError: division by zero
Copy the code

The error message is ZeroDivisionError: Division by Zero. When an error occurs, the program crashes and terminates. The error exception also indicates the number of lines where the error occurred, line 3, in the third line. However, checking the line number for error can not solve the problem directly in many cases, because the error is not on the line number. The efficiency of BUG fixing will generally improve as you learn more about Python.

13.1.2 try… Except the statement

How do you prevent the program from being forced to terminate when something goes wrong and then continue to run? This is try… The scenario used by the except statement.

Syntax format:

try: Error-prone codeexceptException object: Handles exception codeCopy the code

Modify the above code according to the above syntax format.

num1 = 20
num2 = 0
try:
    num3 = num1 / num2
except ZeroDivisionError:
    print("You can't divide by zero.")
Copy the code

At this time, the program will not report an error. When the divisor is found to be 0, it will enter the exception processing and directly output the divisor cannot be 0.

Try means to test for exceptions in the code part, except means to catch exceptions if they occur. Except code does not execute if there are no errors in the try statement.

Another thing to note is that after except is the exception object, which we set as ZeroDivisionError because we already know that this exception will occur. If we do not know what kind of exception will occur in the coding process, the error will still occur.

num1 = 20
num2 = "abc"
try:
    num3 = num1 / num2
except ZeroDivisionError:
    print("You can't divide by zero.")
Copy the code

The above code will still report an error with the following exception:

Traceback (most recent call last):
  File "D:/gun/2/demo7.py", line 4, in <module>
    num3 = num1 / num2
TypeError: unsupported operand type(s) for/ :'int' and 'str'
Copy the code

If you want to support this exception after except, you need to add TypeError.

num1 = 20
num2 = "abc"
try:
    num3 = num1 / num2
except (ZeroDivisionError,TypeError):
    print("You can't divide by zero.")
Copy the code

It can also be written separately:

num1 = 20
num2 = "abc"
try:
    num3 = num1 / num2
except ZeroDivisionError:
    print("You can't divide by zero.")

except TypeError:
    print("Wrong divisor type")
Copy the code

This writing method needs to know in advance what kind of exception will be prompted when writing. If the exception is not clear, you can omit the exception object and directly use the following code.

num1 = 20
num2 = "abc"
try:
    num3 = num1 / num2
except:
    print("You can't divide by zero.")
Copy the code

13.1.3 try… except … Else statements

In the try… An except statement can be followed by an else statement. The meaning of this statement can be interpreted as follows: The code in an except statement is executed when an exception occurs, and the code in an ELSE statement is executed when no exception occurs.

num1 = 20
num2 = 1
try:
    num3 = num1 / num2
except ZeroDivisionError:
    print("You can't divide by zero.")

except TypeError:
    print("Wrong divisor type")

else:
    print("No exception, will be executed.")
Copy the code

If this code is error-free, the else statement will be executed.

13.2 Exception Types

13.2.1 Common Exception Types

As you write code, you need to know some common exception types. Memorizing them can help you quickly troubleshoot errors.

  • AttributeError An object has no attributes
  • Exception Generic Exception object
  • FileNotFoundError cannot find file
  • IOError Indicates that the input or output is abnormal
  • IndexError Indicates an abnormal index
  • KeyError key exception
  • NameError The object name is abnormal
  • SyntaxError indicates a SyntaxError
  • TypeError Indicates an error type
  • ValueError value error

All of the above errors are common, with the Exception object and SyntaxError being the most common.

Most of the time you can just use the generic Exception object, Exception, without having to remember all the Exception types.

13.2.2 Catching Multiple Exceptions

You’ve seen the syntax for catching multiple exceptions in the previous section, so you can look at it again.

try: A block of code that could go wrongexceptThe exception object1: Exception handling code blockexceptThe exception object2: Exception handling code blockCopy the code

13.2.3 An EXCEPT catches multiple exceptions

Python also supports capturing multiple exceptions with an except in the following syntax:

try: A block of code that could go wrongexcept(Exception object1, exception object2...) : Exception handling code blockCopy the code

13.2.4 Throwing an Exception directly

Once you catch an exception, you can throw Python directly to the built-in exception information, such as:

num1 = 20
num2 = 0
try:
    num3 = num1 / num2
except ZeroDivisionError as e:
    print(e)

except TypeError as e:
    print(e)

else:
    print("No exception, will be executed.")
Copy the code

Note that the except exception object is called e using the as keyword, and that e is a built-in error message in Python. Here e can be any name, just follow the variable naming rules.

13.3 finally statement

try … Except statements can also be combined with finally statements to form the following syntax:

try: A block of code that could go wrongexcept: Block of code executed in errorelse: A block of code that normally executesfinally: a block of code that executes whether or not the code has an exceptionCopy the code

The finally syntax needs to be used in conjunction with the try statement, which is executed regardless of whether an exception occurs. You can test the code yourself.

13.4 Logging module

13.4.1 logging modules

In Python, a logging module is provided for better logging of program error information. This module provides five levels for marking the level of log information.

  1. DEBUG level, displayed using logging.debug()
  2. INFO level for logging classes
  3. WARNING Level: Indicates the WARNING level of a potential risk
  4. ERROR level: Raises an ERROR
  5. CRITICAL: causes system problems, the highest level

After importing the logging module, you can use the following to set the level of the display information.

import logging
logging.basicConfig(level=logging.DEBUG)
Copy the code

The five level output functions are as follows:

import logging
logging.basicConfig(level=logging.DEBUG)

logging.debug("DEBUG")
logging.info("INFO")
logging.warning("WARNING")
logging.error("ERROR")
logging.critical("CRITICAL")
Copy the code

The output is as follows:

DEBUG:root:DEBUG
INFO:root:INFO
WARNING:root:WARNING
ERROR:root:ERROR
CRITICAL:root:CRITICAL
Copy the code

Because the level of the above code is set to DEBUG, all log messages are output. If the level is set to WARNING, for example, view the output.

import logging
# Notice the Settings here
logging.basicConfig(level=logging.WARNING)

logging.debug("DEBUG")
logging.info("INFO")
logging.warning("WARNING")
logging.error("ERROR")
logging.critical("CRITICAL")
Copy the code

Because the logging output level is set to WARNING, the DEBUG and INFO levels at lower levels will not be output, which can be improved as the program develops, eventually increasing to CRITICAL.

13.4.2 Formatting log Information

Logging information can be globally formatted in the following syntax:

logging.basicConfig(level=logging.WARNING,format = "")
Copy the code

If the format is not set, the default log information is as follows. Therefore, a DEBUG:root: message is displayed before the output. If format=”” is set, the original log information can be deleted.

DEBUG:root:DEBUG
INFO:root:INFO
WARNING:root:WARNING
ERROR:root:ERROR
CRITICAL:root:CRITICAL
Copy the code

Set format = “” as follows:

import logging
logging.basicConfig(level=logging.WARNING,format= "")
Copy the code

The other content does not need to be modified. The previous default keywords are not displayed in the output log information.

WARNING
ERROR
CRITICAL
Copy the code

For formatting log information, you can also add ascTime, which is time information, such as the following code:

import logging
logging.basicConfig(level=logging.WARNING,format= "%(asctime)s")

logging.debug("DEBUG")
logging.info("INFO")
logging.warning("WARNING")
logging.error("ERROR")
logging.critical("CRITICAL")
Copy the code

The format parameter is asctime. If logging is required, you need to add message. The syntax is as follows:

import logging
logging.basicConfig(level=logging.WARNING,format= "%(asctime)s %(message)s")

logging.warning("WARNING")
logging.error("ERROR")
logging.critical("CRITICAL")
Copy the code

After learning about asctime and Message, you should have a basic understanding of the format syntax. It should be a %(parameter name)s structure. If you add a logging level parameter, levelName, Try it can you concatenate it into format?

13.4.3 Program Log Logging Output to a file

The result is a lot of debugging information on the Python console if the program logs are output to the console. In many cases, the logs can be output to a file, and the implementation is very simple, just add a parameter filename to solve the problem.

import logging
logging.basicConfig(filename = "out.txt",level=logging.WARNING,format= "%(asctime)s %(message)s")
Copy the code

After executing the above code, a log file is automatically generated in the current root directory (files and directories can be set yourself).

13.4.4 Disabling program Logs

Use the following methods to disable logging.

logging.disable(level)
Copy the code

If you want to disable all of them, just limit the level directly to CRITICAL.

import logging
logging.basicConfig(level=logging.WARNING,format= "%(asctime)s %(message)s")
logging.disable(level=logging.CRITICAL)
logging.debug("DEBUG")
logging.info("INFO")
logging.warning("WARNING")
logging.error("ERROR")
logging.critical("CRITICAL")
Copy the code

13.5 Summary of this blog

This blog is about exceptions. Exceptions often occur when writing Python code. Programmers usually call them bugs. Of course, a lot of times we call it “bug-free, no programming.”

Find bugs, solve bugs, programmers are not on the way to write bugs, is on the way to change bugs, friends philosophy.

The exceptions section can be expanded as follows.

  • Raise raises an exception
  • Use the Traceback module to record the exception information in the file
  • Program assert

To learn about Python crawlers, subscribe to the Eraser column and click here to discover surprises


Blogger ID: Dream eraser, hope you like, comment, favorites.