Affirmation
Assertions are programming terms expressed as some Boolean expression that the programmer believes to be true at a particular point in the program.
Use the assert keyword in python , followed by an expression, when the expression is true, the execution will continue, otherwise an AssertionError will be thrown
# test1.py assert 1==2 print('hello') # throw exception AssertionError # test1.py assert 1==1 print('hello') # print hello
abnormal
An exception is a signal that an error occurs when the program is running (logical error). There are two types of errors - syntax errors and logic errors.
Grammatical errors:
#Syntax error example 1 if #Syntax error example 2 def test: pass #Syntax error example 3 print(haha
logical error
#User input is incomplete (for example, the input is empty) or the input is illegal (the input is not a number) num=input(">>: ") int(num) #Cannot complete calculation res1=1/0 res2 = 1 + 'str'
An exception is thrown if an error is found while the program is running
Common exceptions:
AttributeError attempting to access a tree that an object does not have, such as foo.x, but foo has no attribute x IOError input/output exception; basically the file cannot be opened ImportError cannot import module or package; basically path problem or wrong name IndentationError syntax error (subclass of); code is not properly aligned IndexError The subscript index exceeds the sequence boundary, such as trying to access x[5] when x has only three elements KeyError attempting to access a key that does not exist in the dictionary KeyboardInterrupt Ctrl+C is pressed NameError using a variable that has not been assigned to an object SyntaxError Python code is illegal, the code cannot be compiled (personally think this is a syntax error, written wrong) TypeError The incoming object type does not meet the requirements UnboundLocalError attempts to access a local variable that has not been set, basically because there is another global variable with the same name, cause you to think you are accessing it ValueError passes in a value not expected by the caller, even if the value is of the correct type
more exceptions
ArithmeticError AssertionError AttributeError BaseException BufferError BytesWarning DeprecationWarning EnvironmentError EOFError Exception FloatingPointError FutureWarning GeneratorExit ImportError ImportWarning IndentationError IndexError IOError KeyboardInterrupt KeyError LookupError MemoryError NameError NotImplementedError OSError OverflowError PendingDeprecationWarning ReferenceError RuntimeError RuntimeWarning StandardError StopIteration SyntaxError SyntaxWarning SystemError SystemExit TabError TypeError UnboundLocalError UnicodeDecodeError UnicodeEncodeError UnicodeError UnicodeTranslateError UnicodeWarning UserWarning ValueError Warning ZeroDivisionError
exception handling
After the exception occurs, the code after the exception code will not be executed
The python interpreter detects an error and triggers an exception (also allows programmers to trigger exceptions themselves)
The programmer writes specific code specifically to catch this exception (this code has nothing to do with program logic, but with exception handling)
If the capture is successful, enter another processing branch, execute the logic you customized for it, so that the program will not crash, this is exception handling
Why do exception handling
The python parser executes the program. When an error is detected, an exception is triggered. After the exception is triggered and not handled, the program is terminated at the current exception, and the following code will not run. When exception handling is used, the following code will run
How to handle exceptions
First of all, it should be noted that exceptions are caused by program errors. Syntax errors have nothing to do with exception handling and must be corrected before the program runs.
Exception Handling Syntax
Basic syntax:
#try: # Checked code block #except exception type: # Once an exception is detected in try, the logic at this position is executed try: a except NameError: print('NameError') #Execution result NameError try: a except NameError as e: print('NameError') #Execution result NameError name 'a' is not defined #Use as to get the wrong value
The exception class can only be used to handle the specified exception, and it cannot be handled if the exception is not specified.
# The exception is not caught, and the program reports an error directly try: a except IndexError : print('NameError') #Execution result, the error type is NameError instead of IndexError NameError: name 'a' is not defined
multi-branch
s1 = 'hello' try: int(s1) except IndexError as e: print (s) except KeyError as e: print (s) except ValueError as e: print (s) #Run from top to bottom, first find the error type that can be processed, and execute the content in the except
Universal exception
# Universal exception can handle all exceptions, but don't use them indiscriminately. # For errors that have been expected, the specified exception should be used for handling # Universal exception is used to handle unexpected exception types try: num = int(input('Please enter the serial number: ')) except Exception as e: print('Exception') # Universal exception should be placed after all except
try-except-else syntax
The else is followed by the content of the code in the try that does not run abnormally
try: num = int(input('Please enter the serial number: ')) except Exception as e: print('Exception') else: #If the code in the try will not be abnormal, just go to the content of this else print('No problem') print("-----") #operation result #Please enter the serial number: 1 #no problem #----- #abnormal #Please enter the serial number: a #exception #-----
try-except-findlly syntax
The content behind findlly is executed regardless of whether it is abnormal or not.
try: num = int(input('Please enter the serial number: ')) except Exception as e: print('Exception') else: #If the code in the try will not be abnormal, just go to the content of this else print('No problem') finally: print('I will take this regardless of exception or not') #Results of the #Please enter the serial number: 1 #no problem #Whether it's abnormal or not, I'll go with this #abnormal #Please enter the serial number: a #exception #Whether it's abnormal or not, I'll go with this
The use of findlly can be used to close the file, or close the database connection
Actively throw exceptions
Actively throwing exceptions is a way to check whether the code logic or whether it can work properly in some special cases.
Use raise in python to actively throw an exception (an instance of the exception class)
try: raise TypeError('type error') except Exception as e: print (s) #type error
custom exception class
1. Define an exception class, which inherits from the Exception class.
2. Use the raise statement in try to raise exceptions
. 3. Except to catch exceptions and execute related commands.
#_*_coding=UTF-8_*_ #Use a custom exception class to specify the length of the input string #custom exception class class SomeCustomError(Exception): def __init__(self,str_length): super(SomeCustomError,self).__init__() self.str_length = str_length # use custom exception length = input("Enter the specified input string length range:\n") while True: try: s = raw_input("Enter a line of string:\n") #The length of the input string exceeds the specified length range and an exception is thrown if (length < len(s)): raise SomeCustomError(length) except SomeCustomError,x: print("Catch custom exception") print("The re-reading of the input string should be less than %d, please re-enter!" % x.str_length) else: print("The input string is %s" %s) break