程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

24. Python file i/o (II) [exception handling & assertion assert]

編輯:Python

Catalog :

  • Each preface :
  • Python file I/O( Two )
    • Knowledge point supply station :
    • 1.1 exception handling
      • 1.1.1 Throw an exception
      • 1.1.2 Custom exception
      • 1.1.3 python Abnormal system
    • 1.2 expand —— Assertion

Each preface :

  • 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 !

Python file I/O( Two )

Knowledge point supply station :

  • 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

1.1 exception handling

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
  • Catch specific exceptions :
    except After that, you can write to capture the specific exception type ,
    You can also use as Put the captured exception information Stored in the following variables .
  • One try The statement may contain more than one except Clause , To handle different specific exceptions . At most one branch will be executed . But here's the thing try We have to keep up with except Clause !
try:
pass
except TabError:
pass
except NameError:
pass
  • One except Clause can handle multiple exceptions at the same time , These exceptions will be placed in parentheses as a tuple , for example :
except (RuntimeError, TypeError, NameError):
pass
  • the last one except Clause to ignore the name of the exception , It will be used as a wildcard . You can use this method to print an error message , Then throw the exception again .
    such as , We don't have tmp.txt This file , What will the following code output ?
# -*- 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

  • Another example is that we still haven't testfile This file , What will the following code output ? If so, what will be output ? Let's try it by ourselves ~
# -*- 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)

  • About Exception And its Subclass The explanation of :
    The exceptions that will appear in the code are Exception Subclasses of , So in except Just add... At the end Exception that will do ;
    In the process of catching exceptions , It will fall from top to bottom and compare the anomalies in turn , Once you find it, you won't look back .

1.1.1 Throw an exception

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
  • raise The only parameter that specifies the exception to be thrown . It must be an exception instance or an exception class ( That is to say Exception Subclasses of ).
  • If you just want to know if this throws an exception , Don't want to deal with it , So a simple raise Statement can throw it out again .
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 :

  • Put the code that may cause exceptions in try in , You can get the exception , And deal with it accordingly
  • except Used to accept exceptions , And you can throw or return exceptions
  • else When there is no exception, it will execute ,finally No matter whether there is any abnormality , It will be carried out

1.1.2 Custom exception

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
  • Most of the names of exceptions are "Error" ending , It's the same as the standard exception naming .

1.1.3 python Abnormal system

【 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




1.2 expand —— Assertion

Question 1 : How can you force a condition in your code to meet ?
Question two : Is there a special grammar to complete ?

  • Assertion assert
  • Assertion statements are a convenient way to insert debug assertions into your program

assert The grammar rule of :

  • Expression return True Don't complain
  • Expression return False Report errors newspaper AssertionError

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

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved