Day 9 of the Python Foundation Course

Posted by Chantal on Tue, 08 Feb 2022 19:25:42 +0100

Tip: After the article is written, the catalog can be generated automatically, how to generate the help document to the right

Guidance Problem

In practice, the situation we encounter cannot be perfect. For example: a module you wrote
Block, user input does not necessarily meet your requirements; Your program wants to open a file, which may not exist or may not be in the correct format. If you want to read data from the database, it may be empty. Our program runs again, but the memory or hard disk may be full, and so on.

When a software program is running, it is very likely that it will encounter the problems just mentioned, which we call
Exception means exceptions. When we encounter these exceptions, or exceptions, how can we let the written program handle them reasonably without the program crashing? We'll cover these issues in this chapter.


This approach has two disadvantages:

  1. Logic code and error handling code together!
  2. Programmers themselves need to consider more complex exceptions and require more of themselves!

So how do we address anomalies? python's exception mechanism provides us with
Handling method of convenience. If the above is handled using python's exception mechanism, the schematic code is as follows (schematic only, not runnable):

Abnormal Mechanism Essence

Exceptions refer to abnormal phenomena that occur during the running of a program, such as user input errors, division by zero, non-existent files to be processed, array subscripts crossing bounds, and so on.
The so-called exception handling means that a program can still correctly execute the remaining programs in case of a problem without terminating program execution due to an exception.
In python, a number of classes have been introduced to describe and handle exceptions, called exception classes. An exception class definition contains information about the exception and how to handle it. The following shows a more complete hierarchy of inheritance for built-in exception classes in python:

Let's deal with the first exception we encountered:

a=3/0
Traceback (most recent call last):
  File "C:/Users/Lenovo/PycharmProjects/mypro_exception/my01.py", line 1, in <module>
    a=3/0
ZeroDivisionError: division by zero

Process finished with exit code 1

Everything in python is an object, and exceptions are handled as objects. Processing:

  1. Throw an exception: When a method is executed, if an exception occurs, the method generates a representation of that method
    An object of an exception, stops the current execution path, and submits the exception object to the interpreter.
  2. Catch an exception: When the interpreter gets the exception, look for code to handle it.

Attitude to Solving Exceptional Problems

To resolve each anomaly encountered, we recommend that you follow the following three points:

  1. Don't panic, read the information carefully, locate the error. See the reported error message clearly and locate where the error occurred.
  2. Baidu and see ten related posts. Baidu will carry out abnormal information, and view at least ten related posts.
  3. The above two steps still cannot be solved. Ask your teacher and classmates for help.

Key to exception resolution: positioning

When an exception occurs, the interpreter reports related error information and prints it out in the console. We can trace the error back in top-down order to locate the line of code that caused the error.

try...an except structure

try...except is the most common exception handling structure. The structure is as follows:

try:
	Monitored statement blocks that may throw exceptions
except BaseException [as e]:
	Exception handling statement block

A try block contains code that may throw an exception, while an except block is used to catch and handle the exception that occurs. When executed, if no exception is thrown in the try block, the ecept block is skipped and the subsequent code is executed. When executed, if an exception occurs in the try block, the subsequent code in the try block is skipped and the exception is handled in the corresponding except block. After exception handling is complete, continue executing the subsequent code.

The results of the above execution are as follows:

step1
step3
division by zero
step4

[Example] Loop in numbers and handle exceptions if they are not; End the loop until you enter 88.

#Example: Loop in numbers, if not, handle exceptions. Until input 88, the loop ends.

while True:
    try:
        x=int(input("Please enter a number"))
        print("Numbers entered:",x)
        if x==88:
            print("Exit the program")
            break
    except BaseException as e:
        print(e)
        print("Exception, not a number entered")

print("Loop Digital Input Program End!")

Run result:

Please enter a number 66
 Number entered: 66
 Please enter a number asd
invalid literal for int() with base 10: 'asd'
Exception, not a number entered
 Please enter a number 88
 Number entered: 88
 Exit the program
 Loop Digital Input Program End!

try...multiple except structures

The above structure captures all exceptions and is common in work. However, from the classical point of view, it is generally recommended that you try to catch as many exceptions as possible (in the order of descendants followed by parent classes) and write exception handling code specifically. To avoid missing possible exceptions, you can add BaseException at the end. The structure is as follows:

try:
	Monitored statement block that may throw an exception
except Exception1:
	Handle Exception1 Statement block of
except Exception2:
	Handle Exception2 Statement block of
...
except BaseException: 
	Statement blocks that handle exceptions that may be missed

[Example] Multiple except structures

# Test try... Multiple except structures

try:
    a = input("Please enter a dividend")
    b = input("Please enter a divisor")
    c= float(a)/float(b)
    print(c)
except ZeroDivisionError:
    print("abnormal!Cannot divide by 0")
except ValueError:
    print("abnormal!String cannot be converted to a number")
except NameError:
    print("abnormal!Variable does not exist")
except BaseException as e:
    print(e)

Run result:

Please enter a dividend 3
 Please enter a divisor asd
 abnormal!String cannot be converted to a number

Process finished with exit code 0

try...except...else structure

Try...except...else structure with "else block". If no exception is thrown in the try block, the else block is executed. If an exception is thrown in a try block, the except block is executed, and the else block is not executed.

#Test try...except...else structure

try:
    a = input("Please enter a dividend")
    b = input("Please enter a divisor")
    c= float(a)/float(b)
except BaseException as e:
    print(e)
else:
    print(c)

print("Program over!")

Run result:

Please enter a dividend of 5
 Please enter a divisor bbb
could not convert string to float: 'bbb'
Program over!

Process finished with exit code 0

try...except...finally structure

In try...except...finally structure, finally blocks are executed regardless of whether an exception occurs or not; Typically used to release resources requested in a try block.

[Example] try...except...finally simple structure test

#Test try...except...else...finally structure

try:
    a = input("Please enter a dividend")
    b = input("Please enter a divisor")
    c= float(a)/float(b)
except BaseException as e:
    print(e)
else:
    print(c)
finally:
    print("I am finally Executes the statement in")
print("Program over!")

Run result:

Please enter a dividend of 5
 Please enter a divisor asd
could not convert string to float: 'asd'
I am finally Executes the statement in
 Program over!

Process finished with exit code 0

[Example] Reads the file and guarantees closing the file resource in finally

# Test finally

try:
    f=open("d:a.txt","r")
    content=f.readline()
    print(content)
except:
    print("file cannot be found")
finally:
    print("run in finally.close resource")
    try:
        f.close()
    except BaseException as e:
        print(e)
print("End of program execution!")

Run result:

file cannot be found
run in finally.close resource
name 'f' is not defined
 End of program execution!

Process finished with exit code 0

return statement and exception handling problem

Because return serves two purposes: ending the method run and returning a value.
We don't typically put return in the exception handling structure, but at the end of the method.

Resolution of common anomalies

Exceptions in Python are derived from the BaseException class. In this section, we test and list some common exceptions for beginners.

  1. SyntaxError: Syntax error
int a = 3
int a =3
^
SyntaxError: invalid syntax
  1. NameError: Attempt to access an undeclared variable
print(a)
print(a)
NameError: name 'a' is not defined
  1. ZeroDivisionError: Divide by 0 error (divide by zero error)
a = 3/0
a = 3/0
ZeroDivisionError: division by zero
  1. ValueError: Numeric error
float("gaoqi")
float("gaoqi")
ValueError: could not convert string to float: 'gaoqi'
  1. TypeError: Type error
123+"abc"
123+"abc"
TypeError: unsupported operand type(s) for +: 'int' and 'str'
  1. AttributeError: Access properties of an object that do not exist
a=100
a.sayhi()
a.sayhi()
AttributeError: 'int' object has no attribute 'sayhi'
  1. IndexError: Index out of bounds exception
a = [4,5,6]
a[10]
a[10]
IndexError: list index out of range
  1. KeyError: Dictionary keys do not exist
a = {'name':"gaoqi",'age':18}
a['salary']
a['salary']
KeyError: 'salary'

Summary of common anomalies

I suggest you read through and get familiar with the unusually Related words by heart. This can overcome the "fear of difficulty".

Exception Name/Description
Base class for all numeric calculation errors in ArithmeticError
AssertionError Assertion Sentence Failed
AttributeError object does not have this property
Base class for all exceptions to BaseException
DeprecationWarning warning about discarded features
Base class for EnvironmentError operating system errors
EOFError has no built-in input, reaching the EOF tag
Base Class for Exception General Errors
FloatingPointError Floating Point Calculation Error
FutureWarning warning about future semantic changes in construction
GeneratorExit generator exception to notify exit
ImportError failed to import module/object
IndentationError Indentation Error
There is no index in the IndexError sequence
IOError Input/Output operation failed
KeyboardInterrupt user interrupts execution (typically input ^C)
There is no key in the KeyError map
Base class for LookupError invalid data query
MemoryError memory overflow error (not fatal for Python interpreters)
NameError undeclared/initialized object (no properties)
Method not yet implemented by NotImplementedError
OSError Operating System Error
OverflowError numeric operation exceeds maximum limit
Overflow Warning old warning about automatic promotion to long
Pending DeprecationWarning warning that feature will be obsolete
ReferenceError Weak Reference attempts to access objects that have been garbage collected
Runtime Error General Runtime Error
Warning for Runtime Warning suspicious runtime behavior
Base class for all built-in standard exceptions in StandardError
StopIteration iterator has no more values
SyntaxError Python syntax error
SyntaxWarning suspicious syntax warning
SystemError General Interpreter System Error
SystemExit Interpreter Request Exit
TabError Tab Mixed with Spaces
TypeError Invalid Operation on Type
UnboundLocalError accesses uninitialized local variables
Error decoding Unicode DecodeError Unicode
Error encoding UnicodeEncodeError Unicode
UnicodeError Unicode related errors
Error in Unicode TranslateError Unicode conversion
Warning generated by UserWarning user code
ValueError passed in an invalid parameter
Base Class for Warning Warning
WindowsError system call failed
ZeroDivisionError divides (or modifies) by zero (all data types)

with Context Management

finally blocks execute because of exceptions or not, and we usually release code that releases resources. In fact, we can use the context management of with to more easily release resources.

The syntax structure of with context management is as follows:

with context_expr [ as var]: 
Statement block

With context management, resources are automatically managed and the field or context before entering the with code is automatically restored after the execution of the with code block. Jumping out of the with block for any reason, whether or not there is an exception, will always guarantee the normal release of resources. It greatly simplifies the work and is very common in situations related to file operation and network communication.

# Test with Downhill Management Operation

with open("c:/a.txt") as f:
    for line in f:
        print(line)
print("End of program execution!")

Run result:

zhangx

123

xyz
 End of program execution!

Process finished with exit code 0

trackback module

[Example] Print exception information using the Traceback module

#Testing the use of the traceback module

import traceback

try:
    print(step1)
    num=1/0
except:
    with open("c:/a.txt","a") as f:
        traceback.print_exc(file=f)

Exception information is written to the specified TXT file.

Custom exception class

In program development, sometimes we need to define exception classes by ourselves. Custom exception classes are usually run-time exceptions, usually inheriting Exception or its subclasses. Naming is usually suffixed with Error and Exception.

Custom exceptions are thrown actively by raise statements.

[Example] Custom exception classes and raise statements

# Test custom exception classes:

class AgeError(Exception): #Inherit Exception
    def __init__(self,errorInfo):
        Exception.__init__(self)
        self.errorInfo=errorInfo
    def __str__(self):
        return str(self.errorInfo)+",Error in age! Should be at 1-150 Between"

#######Test Code####################
if __name__ =="__main__": #If True, the module runs as a stand-alone file and the test code can be executed
    age=int(input("Enter an age:"))
    if age<1 or age>150:
        raise AgeError(age)
    else:
        print("Normal age:",age)

Run result:

Enter an age: 200
Traceback (most recent call last):
  File "C:/Users/Lenovo/PycharmProjects/mypro_exception/my10.py", line 14, in <module>
    raise AgeError(age)
__main__.AgeError: 200,Error in age! Should be at 1-150 Between

Process finished with exit code 1

Debugging Pycharm Development Environment

The core of debugging is to set breakpoints. When the program reaches the breakpoint, it suspends temporarily and stops execution. Just like watching a video press stop, we can watch every detail of the stop in detail.

breakpoint

The program runs here, suspends temporarily, and stops execution. We can watch the program in detail at this time to make further judgments.

  1. Set breakpoints:
    (1) Add breakpoints by clicking after the line number
    (2) To cancel a breakpoint, click it again

Enter Debug View

There are three ways we can get into the debug view:
(1) Click the button on the toolbar:
(2) Right-click in the editing area and click: debug'module name'
(3) Shortcut keys: shift+F9

When you enter the debug view, the layout is as follows:

Debugging Operating Area

Topics: Python Back-end