The authors introduce :【 Lonely and cold 】—CSDN High quality creators in the whole stack field 、HDZ Core group members 、 Huawei cloud sharing expert Python Full stack domain bloggers 、CSDN The author of the force program
- This article has been included in Python Full stack series column :《Python Full stack basic tutorial 》
- Popular column recommendation :《Django Framework from the entry to the actual combat 》、《 A series of tutorials from introduction to mastery of crawler 》、《 Reptile advanced 》、《 Front end tutorial series 》、《tornado A dragon + A full version of the project 》.
- This column is for the majority of program users , So that everyone can do Python From entry to mastery , At the same time, there are many exercises , Consolidate learning .
- After subscribing to the column But there are more than 1000 people talking privately Python Full stack communication group ( Teaching by hand , Problem solving ); Join the group to receive Python Full stack tutorial video + Countless computer books : Basics 、Web、 Reptiles 、 Data analysis 、 visualization 、 machine learning 、 Deep learning 、 Artificial intelligence 、 Algorithm 、 Interview questions, etc .
- Join me to learn and make progress , One can walk very fast , A group of people can go further !
Be careful :
When an exception occurs in the code , None of the following code will execute ;
The exception itself is a class .
stay Python All exceptions in are inherited from BaseException
Directly divided into four categories :
SystemExit:Python Exit exception ;
KeyboardInterrupt: Keyboard break (Ctrl+C);
GeneratorExit: The generator exits ( As mentioned earlier ~);
Exception: Common exception ( Only this part of the exception will be used ).
The most basic try…except… sentence :
try:
print(11) # That's right , Will print out
print(a) # a No definition , So there will be exceptions
print(22) # Because there is an exception in the above sentence , So even if this sentence is correct , It doesn't print
except:
print(' There's an exception here ')
Output :
11
There's an exception here
try:
Normal operation
except Exception1[, Exception2[,...ExceptionN]]][,Argument]as err:
Something goes wrong , Execute this code
else:
If there is no exception to execute this code
finally:
sign out try Always execute this code
try:
pass
except TabError:
pass
except NameError:
pass
except (RuntimeError, TypeError, NameError):
pass
# -*- coding: utf-8 -*-
""" __author__ = Xiaoming - Code entities """
import sys
try:
f = open('tmp.txt')
s = f.readline()
i = int(s.strip())
except OSError as err:
print("OS error: {0}".format(err))
except ValueError:
print("Could not convert data to an integer.")
except:
print("Unexpected error:", sys.exc_info()[0])
raise
# -*- coding: utf-8 -*-
""" __author__ = Xiaoming - Code entities """
try:
fh = open("testfile", "r")
try:
fh.write(" This is a test file , For testing exceptions !!")
finally:
print(" Close file ")
fh.close()
except IOError as value:
print("Error: File not found or failed to read :", value)
Python Use raise Statement throws a specified exception ( Be careful :raise Is to actively throw the exception type written later ). for example :
>>>raise NameError('HiThere')
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: HiThere
You can write your own custom exceptions :
class WuMou(Exception):
pass
raise WuMou(' There is an error ')
Output is :
Traceback (most recent call last):
File "C:/my/pycharm_work/ceshi.py", line 3, in <module>
raise WuMou(' There is an error ')
__main__.WuMou: There is an error
You can catch this exception :
class WuMou(Exception):
pass
try:
raise WuMou(' There is an error ')
except WuMou as h:
print(h)
Output is :
There is an error
try:
raise NameError('HiThere')
except NameError:
print('An exception flew by!')
raise
Used in conjunction with catching exceptions :
Example :
try:
while True: # You can end the loop
if 1 == 1:
raise NameError(' Something went wrong ')
except Exception as e:
print(e)
Output :
Something went wrong
A small summary :
Exception classes inherit from Exception class , Can inherit directly , Or indirectly , for example :
# -*- coding: utf-8 -*-
""" __author__ = Xiaoming - Code entities """
class MyError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return str(self.value)
try:
raise MyError(2 * 2)
except MyError as e:
print('My exception occurred, value:', e.value)
raise MyError('oops!')
When it is possible to create a module to throw many different exceptions , One common approach is to create a base exception class for this package , Then create different subclasses for different error situations based on this base class :
class Error(Exception):
pass
class InputError(Error):
def __init__(self, expression, message):
self.expression = expression
self.message = message
class TransitionError(Error):
def __init__(self, previous, next, message):
self.previous = previous
self.next = next
self.message = message
【 Official documents ~】
BaseException
+-- SystemExit
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception
+-- StopIteration
+-- StopAsyncIteration
+-- ArithmeticError
| +-- FloatingPointError
| +-- OverflowError
| +-- ZeroDivisionError
+-- AssertionError
+-- AttributeError
+-- BufferError
+-- EOFError
+-- ImportError
| +-- ModuleNotFoundError
+-- LookupError
| +-- IndexError
| +-- KeyError
+-- MemoryError
+-- NameError
| +-- UnboundLocalError
+-- OSError
| +-- BlockingIOError
| +-- ChildProcessError
| +-- ConnectionError
| | +-- BrokenPipeError
| | +-- ConnectionAbortedError
| | +-- ConnectionRefusedError
| | +-- ConnectionResetError
| +-- FileExistsError
| +-- FileNotFoundError
| +-- InterruptedError
| +-- IsADirectoryError
| +-- NotADirectoryError
| +-- PermissionError
| +-- ProcessLookupError
| +-- TimeoutError
+-- ReferenceError
+-- RuntimeError
| +-- NotImplementedError
| +-- RecursionError
+-- SyntaxError
| +-- IndentationError
| +-- TabError
+-- SystemError
+-- TypeError
+-- ValueError
| +-- UnicodeError
| +-- UnicodeDecodeError
| +-- UnicodeEncodeError
| +-- UnicodeTranslateError
+-- Warning
+-- DeprecationWarning
+-- PendingDeprecationWarning
+-- RuntimeWarning
+-- SyntaxWarning
+-- UserWarning
+-- FutureWarning
+-- ImportWarning
+-- UnicodeWarning
+-- BytesWarning
+-- ResourceWarning
Question 1 : How can you force a condition in your code to meet ?
Question two : Is there a special grammar to complete ?
assert The grammar rule of :
Here's a simple example :
a = input(' who are you :')
assert a == ' Wu ',' You are not Wu '
print(' Welcome Wu ')
The first output is :
who are you : Wu
Welcome Wu
The second output is :
who are you : China
Traceback (most recent call last):
File "C:/my/pycharm_work/ceshi.py", line 2, in <module>
assert a == ' Wu ',' You are not Wu '
AssertionError: You are not Wu
An example of upgrading a little :
a = input(' who are you :')
try:
assert a == ' Wu ',' You are not Wu '
print(' Welcome Wu ')
except AssertionError as f:
print(f)
The first output :
who are you : Wu
Welcome Wu
Second output :
who are you : China
You are not Wu