On Errors and Exceptions in python

  • 2021-11-10 10:18:30
  • OfStack

Catalog 1. Syntax Error 2. Exception Handling 2.1, try-finally Statement 2.2, raise Statement 2.3, assert Assertion Statement 3. Summary

1. Syntax errors

Exceptions: Most exceptions will not be handled by the program, and they are presented here in the form of error messages

2. Exception handling


while True:
    try:
        x = int(input(" Please enter 1 Errors: "))
        break
    except ValueError:
        print(" Is not a valid number, try again 1 Pass ")

try statement execution order:

Execute the try statement first. If no exception occurs, ignore the except statement, and the try clause ends after execution. If an exception occurs during the execution of the try clause, the remainder of the try clause is ignored. If the type of the exception matches the name after except, the corresponding except clause is executed. If an exception does not match any except, the exception will be passed to the upper try. (try can be nested with try)

An except clause can handle multiple exceptions at the same time, which will be enclosed in 1 parenthesis as 1 tuple, for example:


except (RuntimeError, TypeError, NameError):
        pass

The last except clause ignores the name of the exception, which will be used as a wildcard. You can use this method to print an error message and then throw the exception again.


except:
    print(" As the last 1 I can catch all exceptions that have not been caught before ")

The try except statement also has an optional else clause, which, if used, must be placed after all except clauses. This clause will be executed when no exception (normal execution) occurs in the try clause. For example:


else:
    print("else Will be executed under normal circumstances ")

Using the else clause is better than putting all the statements inside the try clause, which avoids an unexpected exception that except does not catch.

Exception handling and can also handle exceptions thrown in functions called in clauses (even functions called indirectly). For example:

except... as err; (err is the error type), as can return the error type


def this_fails():
    x = 1 / 0

try:
    this_fails()
except ZeroDivisionError as err:
    print('Handling run-time error:', err)

# Results: Handling run-time error: division by zero

The statement of the finally clause is executed in any case


finally:
    print("finally Write will be executed in any case ")

2.1. try-finally Statement

Syntax:

try:
Statements that may trigger exceptions
finally:
Final statement

Note: finally clause cannot be omitted, 1 definitely does not exist except clause

Function: Do what must be done, and the finally clause will be executed regardless of whether the exception occurs or not

Note: The try-finally statement does not change the (normal/abnormal) state of the program

2.2. raise statement

Function: Trigger an error and let the program enter an abnormal state
Syntax: raise exception type or raise exception object


1 # #raise  Statement 
 2 def make_except():
 3     print(" Begin ...")
 4     # raise ZeroDivisionError  #  Occurs manually 1 Error notifications 
 5     e = ZeroDivisionError(" Divided by zero !!!!!")
 6     raise e  #  Trigger e Binding error , Enter an abnormal state 
 7     print(" End ")
 8 
 9 try:
10     make_except()
11     print("make_except Call complete !")
12 except ZeroDivisionError as err:
13     print(' An error dividing by zero occurred , Processed and turned to normal !')
14     print('err  The bound object is :', err)
15 
16 # Begin ...
17 # An error dividing by zero occurred , Processed and turned to normal !
18 #err  The bound object is :  Divided by zero !!!!!

2.3. assert Assertion Statement

Syntax: assert truth expression, error message (usually string)

Function: If the truth expression is false, actively send out an exception; If the truth expression is true, when the assertion statement does not exist.


assert b==1            #  Or there can be no   Exception description 
assert len(lists) >=5,' The number of list elements is less than 5'        #  When len(lists)<5 Proactively emits an exception when 
assert b==1,'2 Not equal to 1'                        #  When b Not equal to 1 When, actively issue an exception and prompt for an exception 

Use print () function to print out the memory address, indicating that you print out the function name/module name/class name, and need to use the function to take out the value in memory

3. Summary

Receive error message:
try-except
A statement to do something that must be done:
try-finally
Statement to send error message:
raise statement
assert statement

The above is to talk about python errors and exceptions in detail, more information about python errors and exceptions please pay attention to other related articles on this site!


Related articles: