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...finally structure
return statement and exception handling
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 name | interpretative statement |
---|---|
ArithmeticError | Base class for all numeric errors |
AssertionError | Judgment statement failed |
AttributeError | Object does not have this property |
BaseException | Base class for all exceptions |
DepressionWarning | Warning about deprecated features |
EnvironmentError | Base class for operating system error |
EOFError | No built-in input, reaching eof mark |
Exception | Base class for general errors |
FloatingPointError | Floating point calculation error |
FutureWarning | Warnings about future semantic changes in constructs |
GeneratorExit | An exception occurred in the generator and the generator was notified to exit |
ImportError | Failed to import module object |
IndentationError | Indent error |
IndexError | There is no such index in the sequence |
IOError | Input \ output operation failed |
KeyboardInderrupt | User interrupts execution (usually access ^ c) |
KeyError | This key is not in the map |
LookupError | Base class for invalid data query |
MemoryError | Memory overflow error (not fatal for Python interpreter) |
NameError | Undeclared \ initialized object (no properties) |
NotImplementedError | Methods not yet implemented |
OSError | Operating system error |
OverflowError | Numerical calculation exceeds the maximum limit |
PendingDeprecationWarning | Warning that features will be discarded |
OverflowWarning | Old warning about automatic promotion to long integer |
ReferenceError | A weak reference attempts to access an object that has been garbage collected |
RuntimeError | General runtime error |
RuntimeWarning | Warning of suspicious runtime behavior |
StandardError | Base class for all built-in standard exceptions |
StopIteration | The iterator has no more values |
SyntaxError | Python syntax error |
SyntaxWarning | Warning of suspicious syntax |
SystemError | General interpreter system error |
SystemExit | Interpreter requests exit |
TabError | Mixed use of Tab and space |
TypeError | Invalid operation for type |
UNboundLocalError | Accessing uninitialized local variables |
UnicodeDecodeError | Error in Unicode decoding |
UnicodeEncodeError | Error encoding Unicode |
UnicodeError | Unicode related errors |
UnicodeTranslateError | Error converting Unicode |
UserWarning | Warnings generated by user code |
ValueError | Invalid parameter passed in |
Warning | Warning base class |
WindowsError | system call filed |
ZeroDivisionError | Divide 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 '''