Alibaba Cloud Python Training Camp (day3)


Introduction

Anomalies are errors detected during runtime. The computer language defines exception types for possible errors. When a certain error triggers a corresponding exception, the exception handler will be started to restore the normal operation of the program.



One, exception handling

1. Summary of Python standard exceptions

BaseException: the base class of all exceptions
Exception: the base class of regular exceptions
StandardError: the base class of all built-in standard exceptions
ArithmeticError: the base class of all numerical calculation exceptions
FloatingPointError: floating point calculation exception
OverflowError: numerical calculation exceeds the maximum limit
ZeroDivisionError: divisor Zero
AssertionError: Assertion statement (assert)
failed AttributeError: Attempt to access unknown object attribute
EOFError: No built-in input, EOF mark is reached
EnvironmentError: Base class of operating system exception
IOError: Input/output operation failed
OSError: An exception generated by the operating system (For example, opening a non-existent file) WindowsError: system call failed
ImportError: when importing module failed
KeyboardInterrupt: user interrupted execution
LookupError: invalid data query base class
IndexError: index out of the range of sequence
KeyError: find a non-existent in the dictionary Keyword
MemoryError: memory overflow (memory can be released by deleting the object)
NameError: trying to access a non-existent variable
UnboundLocalError: accessing an uninitialized local variable
ReferenceError: Weak reference attempts to access objects that have been garbage collected RuntimeError: General runtime exception
NotImplementedError: Unimplemented method
SyntaxError: Exception caused by syntax error
IndentationError: Exception caused by indentation error
TabError: Tab and space mixed
SystemError: General Interpreter system exception
TypeError: invalid operation between different types
ValueError: incoming invalid parameter
UnicodeError: Unicode related exception
UnicodeDecodeError: exception during Unicode decoding
UnicodeEncodeError: exception caused by Unicode encoding error UnicodeTranslateError: exception caused by Unicode conversion error


2. Summary of Python standard exceptions

Warning: warning base class
DeprecationWarning : warning about deprecated features
FutureWarning: warning about the semantics of the structure will change in the future
UserWarning: warning generated by user code
PendingDeprecationWarning: warning about the feature will be deprecated RuntimeWarning: suspicious runtime Behavior (runtime behavior) warning SyntaxWarning: suspicious syntax warning
ImportWarning: used to trigger a warning in the process of importing a module
UnicodeWarning: warning related to Unicode
BytesWarning: warning related to bytes or bytecode
ResourceWarning: related to resource usage Warning


3.try-except statement

try:
    检测范围
except Exception[as reason]:
    出现异常后的处理代码

The try statement works as follows:

(1). First, execute the try clause (the statement between the keyword try and the keyword except
). (2). If no exception occurs, ignore the except clause and end the try clause after execution.
(3). If an exception occurs during the execution of the try clause, the rest of the try clause will be ignored. If the type of the exception matches the name after except, the corresponding except clause will be executed. Finally execute the code after the try-except statement.
(4). If an exception does not match any except, then the exception will be passed to the upper try.

The demo code is as follows:

try:
    f = open('test.txt')
    print(f.read())
    f.close()
except OSError:
    print('打开文件出错')
#打开文件出错

The try-except-else statement tried to query key-value pairs that were not in the dict, which caused an exception. This exception should belong to KeyError accurately, but because KeyError is a subclass of LookupError and LookupError is placed before KeyError, the program executes the except code block first. Therefore, when using multiple except code blocks, you must insist on the order of their specifications, from the most targeted exception to the most general exception

dict1 = {
    
    'a': 1, 'b': 2, 'v': 22}
try:
    x = dict1['y']
except KeyError:
    print('键错误')
except LookupError:
    print('查询错误')
else:
    print(x)
# 键错误

An except clause can handle multiple exceptions at the same time, and these exceptions will be placed in parentheses as a tuple.


4.try-except-finally statement

try: detection range except Exception[as reason]: processing code after an exception occurs finally: code that will be executed anyway, regardless of whether an exception occurs in the try clause, the finally clause will be executed.

The demo code is as follows:

def divide(x, y):
    try:
        result = x / y
        print("result is", result)
    except ZeroDivisionError:
        print("division by zero!")
    finally:
        print("executing finally clause")

divide(2, 1)
# result is 2.0
# executing finally clause
divide("2", "1")
# executing finally clause
# TypeError: unsupported operand type(s) for /: 'str' and 'str'

If an exception is thrown in the try clause, and there is no except to intercept it, then the exception will be thrown after the finally clause is executed.


5.try-except-else statement

If no exception occurs during the execution of the try clause, Python will execute the statement following the else statement.

try:
    检测范围
except:
    出现异常后的处理代码
else:
    如果没有异常执行这块代码

Use except without any exception type, this is not a good way, we can not identify specific exception information through the program, because it catches all exceptions.

The demo code is as follows:

try:
    fh = open("testfile.txt", "w")
    fh.write("这是一个测试文件,用于测试异常!!")
except IOError:
    print("Error: 没有找到文件或读取文件失败")
else:
    print("内容写入文件成功")
    fh.close()
# 内容写入文件成功

Note: The existence of the else statement must be based on the existence of the except statement. Using the else statement in a try statement without an except statement will cause a syntax error.


6.raise statement

Python uses the raise statement to throw a specified exception.

The demo code is as follows:

try:
    raise NameError('HiThere')
except NameError:
    print('An exception flew by!')
# An exception flew by!    

to sum up

TASK1 content is over, divided into 5 major sections
1. Variables, operators and data types
2. Bit operation
3. Conditional statement
4. Loop statement
5. Exception handling

For these 5 sections, the most difficult one is exception handling. The first four have been learned a lot before. In python, you only need to remember the usage and writing. In
python, the content is not divided by braces, but colons are used. , Novices will make mistakes many times in this regard, so remember.
There is nothing to say about the others. If you don’t, just look at my three-day summary. There are detailed comments on the code.

Guess you like

Origin blog.csdn.net/qq_44250569/article/details/108742618