Python error handling and common built-in modules

One, error handling

1. Python has a built-in error handling mechanism of try...except...finally.... When we think some code may go wrong, we can use try to run this code. If the execution goes wrong, then Subsequent code will not continue to execute, but jump directly to the error handling code, that is, the except statement block. After executing the except, if there is a finally statement block, the finally statement block will be executed. At this point, the execution is complete.

E.g:

try:
    print('try...')
    r = 10 / 0
    print('result:', r)
except ZeroDivisionError as e:
    print('except:', e)
finally:
    print('finally...')
print('END')

The running result is:

try...
except: division by zero
finally...
END

As you can see from the output, when an error occurs, the subsequent statement print('result:', r) will not be executed, except because ZeroDivisionError is caught, so it is executed. Finally, the finally statement is executed. Then, the program continues to go down according to the flow.

If the divisor 0 is changed to 2, the execution result is as follows:

try...
result: 5
finally...
END

Since no error occurs, the except block will not be executed, but finally if there is, it will be executed (there can be no finally statement).

Another advantage of catching errors with try...except is that they can be called across multiple layers. For example, the function main() calls foo(), and foo() calls bar(). As a result, bar() fails. At this time, as long as main() () is captured and can be processed:

def foo(s):
    return 10 / int(s)

def bar(s):
    return foo(s) * 2
def main():
    try:

        bar('0')
    except Exception as e:
        print('Error:', e)
    finally:
        print('finally...')
The result is:

main()Error: division by zero
finally...
2. Call stack:

If the error is not caught, it just keeps going up and is caught by the Python interpreter, prints an error message, and the program exits.

def foo(s):
    return 10 / int(s)

def bar(s):
    return foo(s) * 2

def main():
    bar('0')

main()

The result is:

Traceback (most recent call last):
  File "err.py", line 11, in <module>
    main()
  File "err.py", line 9, in main
    bar('0')
  File "err.py", line 6, in bar
    return foo(s) * 2
  File "err.py", line 3, in foo
    return 10 / int(s)
ZeroDivisionError: division by zero

Interpreting error messages is the key to locating errors. We can see the entire chain of wrong calls from top to bottom:
line 1 of the error message:

Traceback (most recent call last):
Tell us this is wrong tracking information.
Lines 2~3:
 File "err.py", line 11, in <module>
    main()
There is an error calling main(), in line 11 of the code file err.py, but the reason is line 9:
File "err.py", line 9, in main
    bar('0')
There is an error calling bar('0'), in line 9 of the code file err.py, but the reason is line 6:
File "err.py", line 6, in bar
    return foo(s) * 2
The reason is that the statement return foo(s) * 2 is wrong, but this is not the final reason, continue to look down:
 File "err.py", line 3, in foo
    return 10 / int(s)
The reason is that the statement return 10 / int(s) is wrong, which is the source of the error, because the following is printed:
ZeroDivisionError: integer division or modulo by zero
According to the error type ZeroDivisionError, we judge that there is no error in int(s) itself, but int(s) returns 0, and an error occurs when calculating 10 / 0. At this point, the source of the error is found.
3. Record errors

If you don't catch the error, you can have the Python interpreter print the error stack, but the program is terminated. Now that we can catch the error, we can print the error stack, analyze the cause of the error, and let the program continue.
Python's built-in logging module makes logging error messages very easy:

import logging

def foo(s):
    return 10 / int(s)

def bar(s):
    return foo(s) * 2

def main():
    try:
        bar('0')
    except Exception as e:
        logging.exception(e)

main()
print('END')
The same error occurs, but the program will continue to execute after printing the error message and exit normally.

Second, commonly used built-in modules

1,datetime

datetime is Python's standard library for dealing with dates and times.

(1) Get the current date and time
from datetime import datetime

now = datetime.now()
print(now)

print(type(now))

The result is: 2018-04-23 17:38:42.371989 <class 'datetime.datetime'>

Note that datetime is a module, and the datetime module also contains a datetime class, which is imported through from datetime import datetime.
If you only import import datetime, you must refer to the full name datetime.datetime.
datetime.now() returns the current date and time, whose type is datetime.

(2) Get the specified date and time

To specify a date and time, you can construct a datetime directly with parameters:

from datetime import datetime
dt = datetime(2018,4,23,17,41)
print(dt)
结果为:2018-04-23 17:41:00


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324735807&siteId=291194637