Abstract: As a beginner of Python, when you just learn Python programming, you often see some error messages. This article focuses on Python exception handling.

abnormal

  • Errors are broadly classified as errors and exceptions

  • Error is something that can be avoided artificially

  • An exception is a problem that occurs when the syntax and logic are correct

  • In Python, an exception is a class that can be handled and used

Classification of anomalies

BaseException Base class of all exceptions Exception Base class of common errors ArithmeticError Base class of all numeric calculation errors Warning The Warning base class AssertError The assertion statement (Assert) fails AttributeError Attempt to access unknown object properties DeprecattionWarning Warning about deprecated features EOFError User input end-of-file flag EOF (Ctrl+ D) FloattingPointError Floating point calculation error FutureWarning Warning about construction semantics that will change in the future GeneratorExit Generator.close () method ImportError when the import module fails IndexError The index is out of the range of the sequence KeyError KeyboardInterrupt User input Interrupt key (Ctrl+ C) MemoryError Memory overflow (memory can be freed by removing objects) NamerError Attempts to access a non-existent variable NotImplementedError Unimplemented method OSError An exception generated by the operating system (such as opening a nonexistent file) OverflowError The number of operations performed exceeds the upper limit OverflowWarning Old about automatically promoted to long (long) warning PendingDeprecationWarning about characteristics of abandoned warn ReferenceError weak references (weak Reference) attempts to access an object that has already been recycled by garbage collection. RuntimeError RuntimeWarning StopIteration for suspicious runtime behavior Iterators have no more values SyntaxError Python syntax errors SyntaxWarning Warning of suspicious syntax IndentationError TabError Tab and space mixed SystemError Python compiler system error SystemExit The Python compiler process is shut down TypeError Invalid operations between different types UnboundLocalError Access an uninitialized local variable (subclass of NameError) UnicodeError Unicode-related errors (a subclass of ValueError) UnicodeEncodeError Errors during Unicode encoding (a subclass of UnicodeError) UnicodeDecodeError Error during Unicode decoding (subclass of UnicodeError) UserWarning warning generated by user code ValueError passed invalid parameter ZeroDivisionError divisor is zero l = [1,2,3,4,5]# divisor num = int(input("Please input your num: "))print(100/num)Please input your num: 0--------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent Call last) < ipython-input-1-8abb196ce2AA > in <module> 2 # 2 num = int(input("Please input your num: "))----> 4 print(100/num)ZeroDivisionError: division by zeroCopy the code

Exception handling

  • There is no guarantee that the program will always work correctly

  • However, it is important to ensure that the program is properly managed in the worst-case scenario

The syntax for python’s exception handling module is:

· Try :· Try to perform an operation, · If no exception occurs, the task completes · If an exception occurs, throw the exception from the current code block to try to resolve the exception · except exception type 1 :· Solution 1: Used to try to handle the exception here to resolve the problem · except exception type 2: · Solution 2: Used to try to handle exceptions here to resolve the problem · · Except (exception type 1, exception type 2...) : · Solution: Use the same treatment for multiple exceptions · except: · This code will be executed if no exception occurs · finally: · Code that will be executed with or without exceptionsCopy the code
  • process

  • Execute the statement below try

  • If an exception occurs, the exception is handled by looking for the corresponding exception in the except statement

  • If no exception occurs, else statement content is executed

  • Finally, the finally statement is executed regardless of whether an exception occurs

Except (at least one), else and finally are optional

Try: num = int(input("Please input your number:")) RST = 100/num print(" calculate result: {}". Format (RST))except: Print (" input error ") # exit exit()Please input your number:0 Num = int(input("Please input your number:") RST = 100/num print(" {}".format(RST))# {}".format(RST))# {}".format(RST))# Print (" input error ") print(e) # exit Num = int(input("Please input your number:") RST = 100/num print(" {}".format(RST))# {}".format(RST))# {}".format(RST))# {}".format(RST))# {}".format(RST))# {}". Except ZeroDivisionError as e except ZeroDivisionError except ZeroDivisionError as e: Print (" error ") print(e) # exit exit()except NameError as e: print(" error ") print(e) except AttributeError as e: Print (" attribute error ") print(e) exit()# excepttionExcept Exception as e Print (e) except ValueError as e: Print ("NO>>>>>>>>>>>")print("hahaha")Please input your number: FFFF invalid literal for int() with base 10 'ffff'hahahaCopy the code

The user manually raises an exception

  • This can be used when the user wants to raise an exception himself

Raise keyword to raise an exception

# raise example try: Print ("I love you") print(3.1415926) Raise ErrorClassName raise ValueError print(" not done yet ")except NameError as E: print("NameError")except ValueError as e: Print ("ValueError")except Exception as e: print(" ")finally: Print (" I will definitely be executed ")I love you3.1415926ValueError I will definitely be executed # raise case -2# custom exception # note: Custom exceptions must be subclasses of system exceptions. Class DanaValueError(ValueError): pass try: Print ("I love you") 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(" ")finally: Print (" I will definitely be executed ")I love you3.1415926ValueError I will definitely be executed # else statement 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("Exceptiong") Please input your number:0ExceptiongCopy the code

About custom exceptions

  • As long as the raise exception is raised, user-defined exceptions are recommended

  • Customizing exceptions generally includes the following contents:

Customize the exception code in which an exception occurs

User-defined problem prompt after an exception occurs

Customize the number of rows in which an exception occurs

  • The ultimate goal is to make it easier for programmers to quickly locate the error scene if an exception occurs

This article is written by Ruochen in Python For Beginners: Exception Handling Collections.

Click to follow, the first time to learn about Huawei cloud fresh technology ~