abnormal
- Errors in a broad sense can be divided into errors and anomalies
- Mistakes are things that can be avoided
- Exception refers to the premise that the syntax and logic are correct , What happened
- stay python in , An exception is a class , Can handle and use
Classification of exceptions
BaseException The base class for all exceptions
Exception Base class for common errors
ArithmeticError Base class for all numerical errors
Warning The base class for warnings
AssertError Assertions (assert) Failure
AttributeError Trying to access unknown object properties
DeprecattionWarning A warning about abandoned features
EOFError User input end of file flag EOF(Ctrl+d)
FloattingPointError Floating point error
FutureWarning A warning about future semantic changes in construction
GeneratorExit generator.close() When the method is called
ImportError When the import module fails
IndexError Index out of range of sequence
KeyError Look up a nonexistent keyword in the dictionary
KeyboardInterrupt User input interrupt key (Ctrl+c)
MemoryError out of memory ( You can free memory by deleting objects )
NamerError Try to access a variable that doesn't exist
NotImplementedError A method that has not yet been implemented
OSError An exception generated by the operating system ( For example, open a file that doesn't exist )
OverflowError The numerical operation exceeds the maximum limit
OverflowWarning Old about auto promotion to long form (long) Warning of
PendingDeprecationWarning A warning that features will be abandoned
ReferenceError Weak reference (weak reference) Trying to access an object that has been reclaimed by the garbage collection mechanism
RuntimeError General runtime errors
RuntimeWarning Suspicious operational behavior (runtime behavior) Warning of
StopIteration Iterators have no more values
SyntaxError Python A grammatical error of
SyntaxWarning A dubious grammatical warning
IndentationError The indentation error
TabError Tab Mixed with spaces
SystemError Python Compiler system error
SystemExit Python Compiler process is shut down
TypeError Invalid operation between different types
UnboundLocalError Accessing an uninitialized local variable (NameError Subclasses of )
UnicodeError Unicode Related errors (ValueError Subclasses of )
UnicodeEncodeError Unicode Errors in coding (UnicodeError Subclasses of )
UnicodeDecodeError Unicode Error in decoding (UnicodeError Subclasses of )
UserWarning Warnings generated by user code
ValueError Invalid parameter passed in
ZeroDivisionError Divisor is zero.
l = [1,2,3,4,5]
# Divide by zero error
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 # Divide by zero error
3 num = int(input("Please input your num: "))
----> 4 print(100/num)
ZeroDivisionError: division by zero
exception handling
- There is no guarantee that the program will always run correctly
- however , It must be ensured that the problems that the program gets in the worst case are properly managed
python The syntax of the exception handling module is :
try: Try to implement an operation , If nothing goes wrong , The task can be accomplished If there is an anomaly , Throw the exception out of the current code block and try to resolve the exception except Exception types 1: Solution 1: Used to try to handle exceptions here to solve problems except Exception types 2: Solution 2: Used to try to handle exceptions here to solve problems except ( Exception types 1, Exception types 2...): Solution : Use the same handling for multiple exceptions except: If nothing goes wrong , The code here will be executed finally: Code to be executed with or without exception
technological process
- perform try The following statement
- If there is an anomaly , It's in except Statement to find the corresponding abnormal disease for processing
- If nothing goes wrong , execute else Statement content
- Last , Whether or not there is an exception , To perform all finally sentence
- except except( At least one ) outside ,else and finally Optional
# Simple exception cases
try:
num = int(input("Please input your number:"))
rst = 100/num
print(" The result is :{}".format(rst))
except:
print(" Input error ")
# exit It means to quit the program
exit()
Please input your number:0
Input error
# Simple exception cases
# Give tips
try:
num = int(input("Please input your number:"))
rst = 100/num
print(" The result is :{}".format(rst))
# After catching the exception , Instantiate the exception , The error message will be in the instance
# Pay attention to the following
# The following statement is to capture ZeroDivisionError Exception and instantiate instance e
except ZeroDivisionError as e:
print(" Input error ")
print(e)
# exit It means to quit the program
exit()
# Simple exception cases
# Give tips
try:
num = int(input("Please input your number:"))
rst = 100/num
print(" The result is :{}".format(rst))
# If it's multiple error The situation of
# The more specific mistakes we need to make , More and more forward
# In the exception class inheritance relationship , The more subclass exceptions , The more you put it forward ,
# The more the exception of the parent class , The more you put it back 、
# When handling exceptions , Once an exception is intercepted , You will not continue to look down , Go straight to the next
# Code , That is to say finally execute finally sentence , If not, execute the next big statement
except ZeroDivisionError as e:
print(" Input error ")
print(e)
# exit It means to quit the program
exit()
except NameError as e:
print(" Wrong name ")
print(e)
except AttributeError as e:
print(" Property error ")
print(e)
exit()
# Base class for common errors
# If you write the following sentence , Common exceptions will be blocked
# And the following sentence must be the last one excepttion
except Exception as e:
print(" I made a mistake without knowing ")
print(e)
except ValueError as e:
print("NO>>>>>>>>>>>")
print("hahaha")
Please input your number:ffff
I made a mistake without knowing
invalid literal for int() with base 10: 'ffff'
hahaha
The user manually raises an exception
- When something , When the user wants to throw an exception himself , have access to
- raise Keyword to throw an exception
# raise Case study
try:
print("I love you")
print(3.1415926)
# Manually throw an exception
# Pay attention to the grammar :raise ErrorClassName
raise ValueError
print(" It's not over yet ")
except NameError as e:
print("NameError")
except ValueError as e:
print("ValueError")
except Exception as e:
print(" There are abnormal ")
finally:
print(" I'm sure it will be carried out ")
I love you
3.1415926
ValueError
I'm sure it will be carried out
# raise Case study -2
# Custom exception
# We need to pay attention to : Custom exception must be a subclass of system exception
class DanaValueError(ValueError):
pass
try:
print("I love you")
print(3.1415926)
# Manually throw an exception
# Pay attention to the grammar :raise ErrorClassName
raise DanaValueError
print(" It's not over yet ")
except NameError as e:
print("NameError")
# except DanaValueError as e:
# print("DanaError")
except ValueError as e:
print("ValueError")
except Exception as e:
print(" There are abnormal ")
finally:
print(" I'm sure it will be carried out ")
I love you
3.1415926
ValueError
I'm sure it will be carried out
# else Sentence case
try:
num = int(input("Please input your number:"))
rst = 100/num
print(" The result is :{}".format(rst))
except Exception as e:
print("Exceptiong")
else:
print("No Exception")
finally:
print(" I'll be executed anyway ")
Please input your number:0
Exceptiong
I'll be executed anyway
About custom exceptions
- As long as it is raise abnormal , Custom exception is recommended
When customizing exceptions , Generally, it includes the following contents :
- Customize the exception code when an exception occurs
- Customize the question prompt after exception
- Customize the number of rows where an exception occurs
- The ultimate goal is , Once something goes wrong , Convenient for programmers to quickly locate the error site