python notes: exceptions and exception handling

1. Concept of abnormality:

• when the program is running, if the Python interpreter encounters an error, it will stop the execution of the program and prompt some error messages, which is an exception
• the action that the program stops executing and prompts an error message is usually called: raise exception

During program development, it is difficult to deal with all special cases. Through exception capture, we can deal with emergencies in a centralized way, so as to ensure the stability and robustness of the program

2. Catch exceptions

2.1 simple exception catching syntax
• in program development, if the execution of some code is not sure whether it is correct, try can be added to catch exceptions
• the simplest syntax format for catching exceptions:

try:
	The code you are trying to execute is "not sure whether it can execute normally"
except: 
	Write the code that fails the attempt, i.e. the above code cannot be executed normally

Whether there is an exception or not, the code will be executed later

Simple exception capture walkthrough -- requiring the user to enter an integer

try:
	num = int(input("Please enter a number:")) # Prompt the user for a number
except:
	print("Please enter the correct number")

2.2 error type capture

• different types of exceptions may be encountered during program execution, and different responses need to be made for different types of exceptions. At this time, it is necessary to capture the error type
• the syntax is as follows:

try:
# Attempted code pass 
except Error type 1:
	# Corresponding code processing for error type 1
except (Error type 2, Error type 3):
	# Corresponding code processing for error types 2 and 3
except Exception as result:
	print("unknown error %s" % result)

When the Python interpreter throws an exception, the first word in the last line of error message is the error type

Exception type capture walkthrough -- requiring the user to enter an integer

Requirements:
1. Prompt the user to enter an integer
2. Divide 8 by the integer entered by the user and output

try:
	num = int(input("Please enter an integer:")) 
	result = 8 / num
	print(result) 
except ValueError: #Error type 1
	print("Please enter the correct integer") 
except ZeroDivisionError: #Error type 2
	print("Divide by 0 error")

2.3 capturing unknown errors
• during development, it is still difficult to predict all possible errors
• if you want the program not to be terminated because the Python interpreter throws an exception regardless of any error, you can add another exception

The syntax is as follows:

except Exception as result:
	print("unknown error %s" % result)

2.4 complete syntax of exception capture
• in actual development, in order to handle complex exception situations, the complete exception syntax is as follows:

try:
	# Code attempted to execute 
except Error type 1:
	# Corresponding code processing for error type 1
except Error type 2:
	# Corresponding code processing for error type 2  
except (Error type 3, Error type 4):
	# Corresponding code processing for error types 3 and 4
except Exception as result:
	# Print error message print(result) 
else:
	# Code that will execute only if there is no exception pass 
finally:
	# Code that will be executed whether there is an exception or not 
	print("Code that will be executed whether there is an exception or not")

The complete code for catching exceptions in the previous drill is as follows:

try:
	num = int(input("Please enter an integer:")) 
	result = 8 / num
	print(result) 
except ValueError:
	print("Please enter the correct integer") 
except ZeroDivisionError:
	print("Divide by 0 error") 
except Exception as result:
	print("unknown error %s" % result) 
else:
	print("Normal execution") 
finally:
	print("The execution is complete, but it is not guaranteed to be correct")

case1:
Please enter an integer: 8
1.0
Normal execution
The execution is complete, but it is not guaranteed to be correct
case2:
Please enter an integer: 0.2
Please enter the correct integer
The execution is complete, but it is not guaranteed to be correct

3. Abnormal transmission

• exception passing - when an exception occurs in the execution of a function / method, the exception will be passed to the caller of the function / method
• if it is passed to the main program and there is still no exception handling, the program will be terminated

Tips:
• in development, exception capture can be added to the main function
The other functions that are called in the main function are passed to the exception capture of the main function as long as there is an exception.
• in this way, there is no need to add a large number of exception capture in the code, which can ensure the cleanliness of the code

demand
1. Define the function demo1() to prompt the user to enter an integer and return it
2. Define function demo2() and call demo1()
3. call demo2() in the main program.

def demo1():
	return int(input("Please enter an integer:"))

def demo2():
	return demo1()

try:
	print(demo2()) 
except ValueError:
	print("Please enter the correct integer") 
except Exception as result:
	print("unknown error %s" % result)

4. Throw raise exception

• during development, in addition to the exception thrown by the Python interpreter due to code execution errors, it can also actively throw exceptions according to the unique business requirements of the application
• Python provides an Exception exception class [you can also define your own Exception class]
• during development, if you want to throw an exception when meeting specific business requirements, you can:
1. Create an Exception object
2. Use the raise keyword to throw an exception object

try:
	print("Please enter login account: ")
	username = input(">> ")
	if username != "zhangsan":
		raise Exception("User name input error")
	print("Please enter the login password: ")
	password = input(">>: ")
	if (password != "123456"):
		raise Exception("Password input error")
except Exception as e:
	print(e)

Using raise statement to actively throw an exception means that developers can create program exceptions themselves. The program exception here does not refer to system exceptions such as memory overflow and list cross-border access, but refers to problems such as * * the data entered by the user is inconsistent with the required data and user operation errors during the execution of the program, **These problems need the program to deal with and give corresponding tips

assert assertion:
assert statement, also known as assertion statement, can be regarded as a reduced version of if statement. It is used to judge the value of an expression. If the value is true, the program can continue to execute; On the contrary, the Python interpreter will report an assertion error.

The syntax structure of assert statement is:

assert expression [, parameter]

When the expression is true, the program continues to execute;
When the expression is false, the AssertionError error is thrown and the parameter is output

The execution process of assert statement can be represented by if judgment statement, as shown below:

 if expression==True:
    The program continues
else:
    Program report AssertionError: parameter 
def foo(s):
    n = int(s)
    assert n != 0, 'n is zero!'
    return 10 / n

foo('0')

# Code execution results
AssertionError: n is zero!

Keywords: Python

Added by mj99 on Wed, 02 Mar 2022 02:36:26 +0200