Python basic learning

catalogue

Exception - exception mechanism

Brief description of Python exception handling mechanism

try...except... Multiple structures included

try... An except ion structure

try... Multiple except structures

try...except...else structure

try...except...finally structure

return statement and exception handling

Summary of common exceptions

with context management

traceback module

Custom exception class

Exception - exception mechanism

python introduces many classes to describe and handle exceptions

Brief description of Python exception handling mechanism

 

Everything in Python is an object, and exceptions are handled in the way of objects. Process:

When an exception occurs, the interpreter will throw an exception to the current method. 1. If an exception occurs, the interpreter will stop the execution of the method

2. Catch exception: after getting the exception, the interpreter looks for relevant code to handle the exception

The key to the interpreter: positioning

When an exception occurs, the interpreter will report the relevant error information and print the relevant error information on the console. You can trace the process of the error from top to bottom

try...except... Multiple structures included

try... An except ion structure

try... Exception is a 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

# Test try... except... Structure
# Enter a number in the loop. If it is not a number, an exception will be thrown, and enter 21 to end the loop

while True:
    try:
        a = int(input("Please enter a number:"))
        print(a)
        if a == 21:
            break
    except BaseException as e:
        print(e)
        print("Input exception!!!")

print("End of cycle!!!")

'''
Please enter a number: 23
 Output: 23
 Please enter a number: g
 Output: invalid literal for int() with base 10: 'g'
Output: input exception!!!
Please enter a number: 21
 Output: 21
 Output: end of cycle!!!
'''

During execution, if no exception is thrown in the try block, skip the except statement block and continue to execute the subsequent code; If an exception is found in the try during execution, skip the subsequent code in the try statement and jump to the corresponding exception block to handle the exception. After the exception is handled, continue to handle other codes after exception

try... Multiple except structures

The BaseException above can catch all exceptions, but from the perspective of classical theory, it is generally recommended to catch multiple exceptions that may occur (in the order of subclass first and then parent class) and write exception handling code specifically. In order to avoid omitting possible situations, BaseException can be added at the end. The structure is as follows:

try:

Monitored statement blocks that may throw exceptions

except Exception1 :

Statement block handling Exception1

except Exception2 :

Statement block handling Exception2

......

except BaseException :

A statement block that handles exceptions that may be missing

# Test try... Basic usage of multiple except

try:
    a = int(input("Please enter a divisor:"))
    b = int(input("Please enter a divisor:"))
    c = float(a)/float(b)
    print(c)
except ZeroDivisionError :
    print("Exception, 0 cannot be used as divisor")
except ValueError :
    print("Exception. The entered value is not a number and cannot be divided")
except NameError :
    print("Argument does not exist")
except BaseException as e:
    print(e)

print("Output end!!!")
'''
Please enter a divisor: 5
 Please enter a divisor: 0
 Output: exception, 0 cannot be used as divisor
 Output: end of output!!!

Please enter a divisor: g
 Output: exception. The input value is not a number and cannot be divided
 Output: end of output!!!
'''

try...except...else structure

try... except... An "else block" is added to the else structure. If no exception is thrown in the try, the else statement block will be executed. If an exception is thrown in the try, the except statement block will be executed instead of the else statement block. The two are parallel and competitive. The structure is as follows:

try:

Monitored statement blocks that may throw exceptions

except Exception1 :

Statement block handling Exception1

except Exception2 :

Statement block handling Exception2

......

except BaseException :

A statement block that handles exceptions that may be missing

else:

try the statement block executed after normal execution

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

try:
    f = open("d:\\a.txt","r")
    content = f.readline()
    print(content)
except BaseException as e:
    print(e)
else:
    print("Successfully found{0}file".format(f))
f.close()
'''
Output:
1234566

Successfully found<_io.TextIOWrapper name='d:\\a.txt' mode='r' encoding='cp936'>file
'''

try...except...finally structure

try... except... In the finally structure, the finally block will be executed regardless of whether an exception occurs. It is usually used to release the resources applied in the try. The structure is as follows:

try:

Monitored statement blocks that may throw exceptions

except BaseException [as e]:

Exception handling statement block

finally:

Statement block

# Test the try... except... finally statement
import os
try:
    f = open("e:\\a.txt", "r")
    content = f.readline()
    print(content)
except BaseException as e:
    print(e)
finally:
    if os.path.exists("e:\\a.txt"):
        f.close()
    print("End of program execution!!!")
'''
Output:
[Errno 2] No such file or directory: 'e:\\a.txt'
End of program execution!!!
'''

return statement and exception handling

Because return has two functions: ending the operation of a method and returning a value.

Generally, return is not placed in the exception handling structure, but at the end of the method

Summary of common exceptions

Exceptions in Python are derived from BaseException class. Exception summary:

Exception nameinterpretative statement
ArithmeticErrorBase class for all numeric errors
AssertionErrorJudgment statement failed
AttributeErrorObject does not have this property
BaseExceptionBase class for all exceptions
DepressionWarningWarning about deprecated features
EnvironmentErrorBase class for operating system error
EOFErrorNo built-in input, reaching eof mark
ExceptionBase class for general errors
FloatingPointErrorFloating point calculation error
FutureWarningWarnings about future semantic changes in constructs
GeneratorExitAn exception occurred in the generator and the generator was notified to exit
ImportErrorFailed to import module object
IndentationErrorIndent error
IndexErrorThere is no such index in the sequence
IOErrorInput \ output operation failed
KeyboardInderruptUser interrupts execution (usually access ^ c)
KeyErrorThis key is not in the map
LookupErrorBase class for invalid data query
MemoryErrorMemory overflow error (not fatal for Python interpreter)
NameErrorUndeclared \ initialized object (no properties)
NotImplementedErrorMethods not yet implemented
OSErrorOperating system error
OverflowErrorNumerical calculation exceeds the maximum limit
PendingDeprecationWarningWarning that features will be discarded
OverflowWarningOld warning about automatic promotion to long integer
ReferenceErrorA weak reference attempts to access an object that has been garbage collected
RuntimeErrorGeneral runtime error
RuntimeWarningWarning of suspicious runtime behavior
StandardErrorBase class for all built-in standard exceptions
StopIterationThe iterator has no more values
SyntaxErrorPython syntax error
SyntaxWarningWarning of suspicious syntax
SystemErrorGeneral interpreter system error
SystemExitInterpreter requests exit
TabErrorMixed use of Tab and space
TypeErrorInvalid operation for type
UNboundLocalErrorAccessing uninitialized local variables
UnicodeDecodeErrorError in Unicode decoding
UnicodeEncodeErrorError encoding Unicode
UnicodeErrorUnicode related errors
UnicodeTranslateErrorError converting Unicode
UserWarningWarnings generated by user code
ValueErrorInvalid parameter passed in
WarningWarning base class
WindowsErrorsystem call filed
ZeroDivisionErrorDivide by (modulo) 0 (all data types)

with context management

try... In a series of structures, the finally block will be executed whether there is an exception or not. It is usually used to release resources

Structure:

with context_expr [as var]:

Statement block

With context management can automatically manage resources, automatically restore the scene or context before entering the code after the execution of the with code block, and always ensure the normal release of resources when jumping out of the with block for any reason, whether there are exceptions or not. It is often used in occasions related to file operation and network communication

# Test with statement (not to replace try... except... finally, but to be used in file operation management and network communication)
with open("E:\\codeblock..cc\\1.cpp\\a.txt", "r") as f:
    content = f.readline()
    print(content)
'''
Output:
full name=Xiao Wang, age=20,Gender=male
'''

traceback module

Use traceback module to print exception information

import traceback

try:

print("xxxxxx")

num = 1/0

except:

traceback.print_exc()

# Test traceback module usage
import traceback

try:
    print("x"*10)
    a = 1/0
except BaseException:
    with open("E:\\codeblock..cc\\1.cpp\\a.txt","a") as f:
        traceback.print_exc(file=f)
'''
Output:
XXXXXXXXXX
'''

Custom exception class

In program development, you sometimes need to define your own Exception class. Generally, the runtime Exception usually inherits Exception or its subclass, and the name is generally suffixed with Error and Exception

The user-defined exception is actively thrown with raise statement

# Test custom exception class
class AgeError(Exception):
    def __init__(self, errorinfo):
        Exception.__init__(self)
        self.errorinfo = errorinfo
    def __str__(self):
        return str(self.errorinfo)+",Wrong age, age should be 1-150 between"

##########Test code#############


if __name__ =="__main__":  # If TRUE, the file is run as a stand-alone module and the test code can be executed
    age = int(input("Please enter an age:"))
    if age < 0 or age > 150:
        raise AgeError(age)
    else:
        print(age)
'''
Please enter an age: 200
 Output: Traceback (most recent call last):
 	 File "E:\python project\py project 01\mypy20.py", line 15, in <module>
   	 raise AgeError(age)
	__main__.AgeError: 200,Wrong age, age should be 1-150 between
'''

Keywords: Python Back-end

Added by snteran on Sat, 05 Feb 2022 05:41:21 +0200