Python study day 31 (abnormalities, abnormal capture)

About elective procedures, indeed, a bit busy recently, no chance to review os, pickle module in two parts, the dictionary data storage and reading becomes a problem, roughly know the principle, but the specific operation may still have to go back and take another look, so now in advance to start learning new knowledge, although today feeling associated methods of str forget is clean, but I have pycharm.

Today, the main content is about feeling abnormal, in fact, a bit like the beginning just learned, is relatively simple.

  An exception is the error signal generation program is running (when the program error occurs, an exception, if the program does not handle it, it will throw the exception, run the program also will be terminated), in python, false triggering exceptions are as follows:

 

 

   Errors are divided into two types:

  1. syntax errors, basic pycharm will help you show up, should not commit

  2. Logical errors, not easy to see, pycharm regardless, the Python interpreter is only love, but have to wait until the time is really running

# TypeError: int type is not the iteration 
for I in . 3 :
     Pass 
# a ValueError 
NUM = INPUT ( " >>: " ) # input Hello 
int (NUM) 

# NameError 
AAA 

# IndexError 
L = [ ' Egon ' , ' AA ' ] 
L [ . 3 ] 

# a KeyError 
DIC = { ' name ' : ' Egon ' } 
DIC [ ' Age ' ] 

#AttributeError 
class Foo: Pass 
foo.x 

# the ZeroDivisionError: Unable to complete the calculation 
RES1 =. 1/ 0 
RES2 = +. 1 ' STR '
 
2. logical errors

  The following are the most important part of today:

  Different anomalies in python may be of different types (classes and python unified type, i.e. the type of category) to identify an abnormality flag wrong

  The following are commonly used exception:

AttributeError no attempt to access an object tree, such as foo.x, but foo does not attribute the X- 
IOError input / output abnormalities; basically can not open the file 
ImportError not import module or package; basically a question or path name is wrong 
IndentationError syntax error (subclass); the code is not properly aligned 
IndexError subscript index out of sequence boundaries, such as when only three elements of x, is trying to access x [ . 5 ] 
a KeyError attempts to access the dictionary does not exist in the bond 
the KeyboardInterrupt the Ctrl + C is pressed 
NameError use a variable has not been given an object 
SyntaxError Python code is illegal, the code does not compile (personally think it's a syntax error, wrong) 
TypeError incoming object type does not comply with the requirements of 
UnboundLocalError attempt to access a local variable has not been set , basically due to a global variable otherwise the same name, 
led to think that you are accessing it 
ValueError incoming caller does not expect a value, even if the value of the type is correct 

common abnormalities

  More abnormal (or to free one by one wrong again):

ArithmeticError
AssertionError
AttributeError
BaseException
BufferError
BytesWarning
DeprecationWarning
EnvironmentError
EOFError
Exception
FloatingPointError
FutureWarning
GeneratorExit
ImportError
ImportWarning
IndentationError
IndexError
IOError
KeyboardInterrupt
KeyError
LookupError
MemoryError
NameError
NotImplementedError
OSError
OverflowError
PendingDeprecationWarning
ReferenceError
RuntimeError
RuntimeWarning
StandardError
StopIteration
SyntaxError
SyntaxWarning
SystemError
SystemExit
TabError
TypeError
UnboundLocalError
UnicodeDecodeError
UnicodeEncodeError
UnicodeError
UnicodeTranslateError
UnicodeWarning
UserWarning
ValueError
Warning
ZeroDivisionError

更多异常

  To ensure the robustness and fault-tolerance program, that program does not crash when it encounters an error, we need to deal with exceptions,

   If the error condition is predictable, we need to deal with if: prevention before the error occurred

  Before the operation also have had:

= 10 of AGE
 the while True: 
    age = INPUT ( ' >>: ' ) .strip ()
     IF age.isdigit (): # Only when a string is an integer of age, the following code will not an error, the condition is predict 
        Age = int (Age)
         IF Age == of AGE:
             Print ( ' you GOT IT ' )
             BREAK

If the error condition is unpredictable, you need to use try ... except: processing after an error

# Basic syntax of 
the try : 
    code block to be detected 
except exception types: 
    the try in the event of an anomaly is detected, the logic of the implementation of this position 
# example 
the try : 
    F = Open ( ' a.txt ' ) 
    G = (line.strip () for Line in F)
     Print (Next (G))
     Print (Next (G))
     Print (Next (G))
     Print (Next (G))
     Print (Next (G))
 the except the StopIteration: 
    f.close ()

  

# 1 exception class can only be used to handle specific exceptions, if you can not deal with non-specified exception. 
S1 = ' Hello ' 
the try : 
    int (S1) 
the except IndexError AS E: # uncaught exception, the program directly given 
    Print E 

# 2 multibranched 
S1 = ' Hello ' 
the try : 
    int (S1) 
the except IndexError AS E:
     Print (E )
 the except a KeyError AS E:
     Print (E)
 the except a ValueError AS E:
     Print (E) 

# . 3 universal exception exception 
S1 = ' Hello ' 
the try :
    int (s1) 
the except Exception AS E:
     Print (E) 

# 4 multi-branch abnormalities and abnormal universal 
# 4.1 if you want the effect, no matter what is abnormal, we unified discarded, or use the same code logic to deal with them, so show in bold to do it, there is only one Exception enough. 
# 4.2 if you want to effect that, for different exception we need to customize different processing logic, it would need to use a multi-branch. 

# 5 may be a multi-branch later a Exception 
S1 = ' Hello ' 
the try : 
    int (S1) 
the except IndexError AS E:
     Print (E)
 the except a KeyError AS E:
     Print (E)
 the except a ValueError AS E:
     Print (E)
 the except Exception E AS:
     Print (E)

# 6 abnormality others 
S1 = ' Hello ' 
the try : 
    int (S1) 
the except IndexError AS E:
     Print (E)
 the except a KeyError AS E:
     Print (E)
 the except a ValueError AS E:
     Print (E)
 # the except Exception AS E: 
#     Print (E) 
the else :
     Print ( ' within a try code block is executed no exceptions I ' )
 a finally :
     Print ( ' whether abnormal or not, the module will be executed, usually carried out clean-up ' ) 

# 7 active trigger abnormal 
try:
     The raise TypeError ( ' type error ' )
 the except Exception AS E:
     Print (E) 

# . 8 custom exception 
class EgonException (BaseException):
     DEF  the __init__ (Self, MSG): 
        self.msg = MSG
     DEF  __str__ (Self):
         return Self a .msg 

the try :
     The raise EgonException ( ' type error ' )
 the except EgonException AS E:
     Print (E) 

# . 9 asserts: assert condition 
assert . 1. 1 ==  
the Assert 1 == 2 # 10 summarizes try..except

 Abnormal catch advantages:

1: error handling and the real work separate
2: code easier to organize, clearer and complex tasks easier to implement;
3: Without a doubt, more secure, and will not for some minor oversight the program unexpectedly crash a;

 

Mainly theoretical knowledge, the latter use is the key, just like I want to review the pickle and os modules, That's it.

Guess you like

Origin www.cnblogs.com/xiaoyaotx/p/12563464.html