abnormal

  • In a broad sense, errors are divided into errors and exceptions
  • Errors are things that can be avoided
  • An exception is a problem that occurs when the syntax and logic are correct
  • In Python, an exception is a class that you can handle and use

Classification of anomalies

BaseException base class for all exceptions Exception base class for common errors ArithMeticError base class for all numerical computation errors Warning base class AsserTerror Assert statement failed AttributeError Attempts to Access Unknown Object Attribute DeprecattionWarning about deprecated features EOFERROR User input End of file flag EOF (CTRL + D) FloatingPointerError floating-point computation error FutureWarning warning about construction of future semantic changes GeneratoreXit Generator.close () method when called IndexError index is out of sequence when Imerror import module fails KeyboardInterrupt User input key (CTRL + C) MemoryError Memory overflow (memory can be freed by deleting an object) NameError attempts to access a variable that does not exist NotimplementeError yet to be implemented method OSrorException generated by the operating system (such as opening a file that does not exist) OverflowError value operation exceeds maximum limit OverflowWarning Old about automatically promoted to long (long) warning PendingDeprecationWarning about characteristics of abandoned warn ReferenceError weak references (weak reference) trying to access a garbage collection has been recycled objects A RuntimeWarning for a suspect runtime behavior is stopIteration. There are no more values for the Iterator. SyntaxError Python SyntaxError SyntaxWarning SuspiciousSyntax Warning IndentationError Indent Error TabError Mixed Tab and Spaces Using Systemerror Python Compiler SystemError SystemExit Python Compiler Process shut down TypeError Invalid operation between different types UnboundLocalError accessing an uninitialized local variable (a subclass of NameError) UnicodeError Unicode-related error (a subclass of ValueError) UnicodeEncodeError (a subclass of UnicodeError) UnicodeDecodeError (a subclass of UnicodeError) UserWarning (a subclass of UnicodeError) User-codegenerated warning ValueError passed in an invalid parameter with a ZeroDivisionError divisor of zero
Num = int(input("Please input your num: ")) print(100/num) print(100/num)
Please input your num: 0 --------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent Call last) <ipython-input-1-8abb196ce2aa bb0 in <module> 2 # 3 num = int(input("Please input your num: ")) ----> 4 print(100/num) ZeroDivisionError: division by zero

Exception handling

  • There is no guarantee that a program will always run correctly
  • However, it is important to ensure that the program’s worst-case problems are properly managed
  • The full syntax of the Python exception-handling module is:

    try: Attempts to implement an action, if no exception occurs, the task is completed. If an exception occurs, throw the exception from the current code block. Attempts to resolve the exception. Used to try to handle the exception here to solve the problem except (Exception type 1, Exception type 2...) Except: If there are no exceptions, this code finally: The code that should be executed if there are no exceptions will be executed
  • process

    1. Execute the statement under try
    2. If there is an exception, find the corresponding exception in the except statement for processing
    3. If no exception occurs, the contents of the else statement are executed
    4. Finally, the finally statement is executed regardless of whether an exception occurs
  • Except except except (at least one), else and finally are optional
Try: num = int(input("Please input your number:")) RST = 100/num print(". Format (RST)) except: Print (" error ") # exit exit() print(" error ") # exit
Please input your number:0
Try () {try () {try (); Num = int(input("Please input your number:")) RST = 100/num print(" {}".format(RST)) # catch ZeroDivisionError (except ZeroDivisionError as E) {}".format(RST)) # catch ZeroDivisionError (except ZeroDivisionError as E) Print (e) # exit() print(e) # exit()
Try () {try () {try (); Num = int(input("Please input your number:")) RST = 100/num print(" {}".format(RST)) # If there are multiple errors, the more specific the error is, the more the exception is in the subclass, the more the exception is in the superclass, the more the exception is. Then proceed directly to the next # code, that is, execute finally statement if finally exists, or execute the next large statement except ZeroDivisionError as e: Print (e) print(e) # exit exit() except NameError as e: print(e) except AttributeError as e: Print (" property error ") print(e) exit() # base class for common error Print (e) except ValueError as e: print("NO>>>>>>>>>>>") print("hahaha") print("hahaha")
Invalid literal for int() with base 10: 'FFFF' hahaha

The user manually throws an exception

  • This can be used when the user wants to throw an exception himself
  • The raise keyword is used to raise an exception
# raise case try: Print ("I love you") print(3.1415926) print(3.1415926) Raise errorClassName Raise ValueError print(" not yet ") except NameError as e: print("NameError") except ValueError as e: Print (" valueError ") except Exception as E: print(" There is an Exception ") finally: print(" I will be executed ")
I love you 3.1415926 ValueError I will definitely be executed
Note: The custom exception must be a subclass of the system exception Class DanaValueError(valueError): pass try: Print ("I love you") print(3.1415926) print(3.1415926) Raise errorClassName Raise danavalueError print(except NameError as E: print("NameError") # except DanaValueError as e: # print("DanaError") except ValueError as e: Print (" valueError ") except Exception as E: print(" There is an Exception ") finally: print(" I will be executed ")
I love you 3.1415926 ValueError I will definitely be executed
# else try: Num = int(input("Please input your number:")) RST = 100/num print(" {}". Format (RST)) except Exception ase: Print ("Exceptiong") else: print("No Exception") finally: print(" I will be executed anyway ")
Please input your number:0 Exceptiong anyway I will be executed

About custom exceptions

  • As long as the Raise exception is present, custom exceptions are recommended
  • When customizing an exception, it usually includes the following:

    • Customize the exception code where the exception occurs
    • Customize the problem prompt after an exception occurs
    • Customize the number of rows in which an exception occurs
  • The ultimate goal is to make it easy for programmers to quickly locate the error scene once an exception occurs