1/ What is an error and what is an exception?
Errors are broadly classified as errors and exceptions. An error is something that can be avoided, which means you can know in advance that it's a mistake. Exceptions are problems that may occur if the syntax and logic are correct. That is, something that can't be predicted in advance. In cases where we can't predict ahead of time, we can improve the code's fault tolerance by thinking about possible problems. In Python, an exception is a class that can be handled and usedCopy the code
2/ 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 assertion statement (Assert) failed AttributeError Attempts to access unknown object attributes DeprecattionWarning Warning about deprecated features EOFError User input end-of-file flag EOF (Ctrl+ D) FloattingPointError Floating point calculation error FutureWarning Warning that building semantics will change in the future when the GeneratorExit Generator.close () method is called ImportError When the import module fails IndexError index is out of range of the sequence KeyboardInterrupt User input Interrupt key (Ctrl+ C) MemoryError Memory overflow (memory can be freed by deleting objects) NamerError Attempts to access a variable that does not exist NotImplementedError An unimplemented method OSError An exception generated by the operating system (such as opening a nonexistent file) OverflowError A value operation exceeds the upper limit OverflowWarning Old about automatically promoted to long (long) warning PendingDeprecationWarning about characteristics of abandoned warn ReferenceError weak references (weak reference) trying to access a garbage collection has been recycled objects RuntimeError RuntimeWarning Warning of suspicious runtime behavior StopIteration Iterators have no more values SyntaxError Python syntax errors SyntaxWarning IndentationError TabError Tab and space mixed SystemError Python compiler SystemError SystemExit the Python compiler process is shut down TypeError Invalid operations between different types UnboundLocalError Accessing an uninitialized local variable (subclass of NameError) UnicodeError Unicode-related error (subclass of ValueError) UnicodeEncodeError Error during Unicode encoding (subclass of UnicodeError) UnicodeDecodeError Error during Unicode decoding (subclass of UnicodeError) UserWarning User code generated warning ValueError passed invalid parameter ZeroDivisionError divisor is zeroCopy the code
3/ Exception handling
With a piece of code, we can guess what might go wrong, but we can't be sure, which means we can't guarantee that the program will always work correctly. However, we must ensure that the program is properly managed when it encounters problems that cannot be known in advance, so we must write in our code what to do if we encounter a problem.Copy the code
The syntax of the exception handling module in Python is:
try: Try to perform an operation, if no exception occurs, the task is complete, and then perform the followingelseStatement block, executed lastfinallyIf an exception occurs in a statement block, throw the exception from the current code block in an attempt to resolve the exceptionexceptException types1:# if exception type 1,......The solution1: used to try to handle exceptions here to resolve the problemexceptException types2:If the exception type is 2,......The solution2: used to try to handle exceptions here to resolve the problemexcept(Exception type1, exception type2...) :If it is an exception of type 1 or 2,......Solution: Use the same handling for multiple exceptionsexcept:If a try fails, whatever the problem is, execute the block
If a try fails, whatever the problem is, execute the block
else: Code that executes without exceptionsfinally: Code that executes regardless of exceptions# process
Execute the statement below try
If an exception occurs, look for the exception disease in the except statement block.Execute if no exception we wrote is hitexceptStatement, and finally executes the finall statement# If no exception occurs, else and finally statements are executed.
#else is code that executes without encountering an exception
# Except (at least one), else and finally are optional
Copy the code
4/ Code examples
A simple exception can be used as follows:
try:
num = int(input("Please input your number:"))
rst = 100/num
print("The calculated result is: {}".format(rst))
except: # error type = 'error';
print("Input error")
# exit means to exit the program
exit()
The result is:
Please input your number:0Input errorCopy the code
# Simple exception case
# Give a hint
try:
num = int(input("Please input your number:"))
rst = 100/num
print("The calculated result is: {}".format(rst))
After catching the exception, instantiate the exception, the error message will be in the instance
# Note the following
The following statement catches ZeroDivisionError and instantiates instance e
except ZeroDivisionError as e:
print("Input error")
print(e)
# exit means to exit the program
exit()
Copy the code
# Simple exception case
# Give a hint
try:
num = int(input("Please input your number:"))
rst = 100/num
print("The calculated result is: {}".format(rst))
# If there are multiple errors
The more specific the error, the further forward
# In the exception class inheritance relationship, the more subclasses of exceptions, the more forward,
# The more superclass exception, the later the exception,
Once an exception is intercepted, proceed directly to the next exception
If finally is present, the finally statement is executed. If not, the next large statement is executed
except ZeroDivisionError as e:
print("Input error")
print(e)
# exit means to exit the program
exit()
except NameError as e:
print("Accessed a variable that does not exist.")
print(e)
except AttributeError as e:
print("Attribute error")
print(e)
exit()
Common error base class
# If you write the following sentence, common exceptions will be blocked
The following sentence must be the last excepttion
# Exception is the base class for common errors. Except Exception as e when you do not know what will go wrong, you can use except Exception as e
except Exception as e:
print("I don't know. I made a mistake.")
print(e)
except ValueError as e:
print("NO>>>>>>>>>>>")
print("hahaha")
The result is:
#Please input your number:ffff
# I don't know, I made a mistake
#invalid literal for int() with base 10: 'ffff'
#hahaha
Copy the code
The user manually raises an exceptionCopy the code
About the custom exception As long as it is raise exceptions, custom exception is preferred At the time of custom exception, generally include the following contents: exception code of a custom exception occurs The custom question prompt after an exception occurs The custom exception occurs is the number of rows of the final purpose, once an exception occurs, convenient programmers fast positioning errorCopy the code