abnormal
- Errors are broadly classified as errors and exceptions
- Error is something that can be avoided artificially
- An exception is a problem that occurs when the syntax and logic are correct
- In Python, an exception is a class that can be handled and used
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
l = [1.2.3.4.5]
# error dividing by zero
num = int(input("Please input your num: "))
print(100/num)
Copy the code
Please input your num: 0 --------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent Call last) < ipython-input-1-8abb196ce2AA > in <module> 2 # 2 num = int(input("Please input your num: ")) ----> 4 print(100/num) ZeroDivisionError: division by zeroCopy the code
Exception handling
-
There is no guarantee that the program will always work correctly
-
However, it is important to ensure that the program is properly managed in the worst-case scenario
-
The syntax for python’s exception handling module is:
try: Except Exception type 1: Solution 1: Used to try to handle the exception here To resolve the problem Except exception type 2: Solution 2: Except (Exception type 1, exception type 2...) Except: This code will be executed if no exception occurs. Finally: This code will be executed with or without exceptionsCopy the code
-
process
- Execute the statement below try
- If an exception occurs, the exception is handled by looking for the corresponding exception in the except statement
- If no exception occurs, else statement content is executed
- Finally, the finally statement is executed regardless of whether an exception occurs
-
Except (at least one), else and finally are optional
# Simple exception case
try:
num = int(input("Please input your number:"))
rst = 100/num
print("The calculated result is: {}".format(rst))
except:
print("Input error")
# exit means to exit the program
exit()
Copy the code
Please input your number:0 The input is incorrectCopy 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("Wrong name.")
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
except Exception as e:
print("I don't know. I made a mistake.")
print(e)
except ValueError as e:
print("NO>>>>>>>>>>>")
print("hahaha")
Copy the code
Invalid literal for int() with base 10: 'FFFF' hahahaCopy the code
The user manually raises an exception
- This can be used when the user wants to raise an exception himself
- Raise keyword to raise an exception
# raise case
try:
print("I love you")
print(3.1415926)
Manually raise an exception
Raise ErrorClassName 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("Abnormal")
finally:
print("I'm sure I'll be executed.")
Copy the code
I love you 3.1415926 ValueError I will definitely be executedCopy the code
# raise Example -2
# Custom exception
Note: Custom exceptions must be subclasses of system exceptions
class DanaValueError(ValueError) :
pass
try:
print("I love you")
print(3.1415926)
Manually raise an exception
Raise ErrorClassName 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("Abnormal")
finally:
print("I'm sure I'll be executed.")
Copy the code
I love you 3.1415926 ValueError I will definitely be executedCopy the code
# else statement case
try:
num = int(input("Please input your number:"))
rst = 100/num
print("The calculated result is: {}".format(rst))
except Exception as e:
print("Exceptiong")
else:
print("No Exception")
finally:
print("I'll be executed anyway.")
Copy the code
Please input your number:0 Exceptiong anyway I will be executedCopy the code
About custom exceptions
- As long as the raise exception is raised, user-defined exceptions are recommended
- Customizing exceptions generally includes the following contents:
- Customize the exception code in which an exception occurs
- User-defined problem prompt after an exception occurs
- Customize the number of rows in which an exception occurs
- The ultimate goal is to make it easier for programmers to quickly locate the error scene if an exception occurs