Exception handling for the basic objects of the Python

A . Recognize abnormal

1. The following are common types of errors given exception :

IndexError sequence index out of range

KeyError dictionary lookup key does not exist

It NameError tries to access a variable that does not exist

IndentationError indentation errors

AttributeError try to access an unknown object properties

StopIteration iterator no more value

AssertionError assertion (assert) failure

EOFError user input end of file marker EOF (Ctrl + d)

FloatingPointError floating point calculation error

GeneratorExit generator.close () method is called when

Import module failed when ImportError

KeyboardInterrupt user input interrupt key (Ctrl + c)

MemoryError memory overflow (can release memory by deleting objects)

Methods NotImplementedError unfulfilled

Abnormalities (e.g., open a file that does not exist) operating system produced OSError

Exceeds the maximum limit value calculation OverflowError

ReferenceError weak reference (weak reference) has been recovered trying to access a garbage collection objects

RuntimeError general run-time error

SyntaxError Python syntax errors

TabError Tab and spaces mix

SystemError Python compiler system error

SystemExit Python compiler process is closed

Invalid operation between different types TypeError

UnboundLocalError access an uninitialized local variables (NameError subclass)

UnicodeError Unicode related errors (ValueError subclass)

UnicodeEncodeError Unicode error (a UnicodeError subclass) for coding

UnicodeDecodeError Unicode error (a UnicodeError subclass) when decoding

UnicodeTranslateError Unicode error (a UnicodeError subclass) when conversion is

Invalid parameter passed ValueError

ZeroDivisionError divide by zero

2. some of the more common error above as an example for

# (1) IndexError sequence index out of the range of
# LST = [1,2,3,4,5]
# RES = LST [999]

# (2) a KeyError dictionary search key does not exist
dic = { 'a ':. 1,' B ': 2,' C ':. 3}
# Print (DIC [ "D"])

# (. 3) NameError attempt to access a nonexistent variable
#Print (HHH)

# (. 4) IndentationError indented error
IF. 5 ==. 5:
    Print (55)
  # Print (444)


# (. 5) tries to access the location AttributeError object attribute
class MyClass ():
    a =. 5
    B =. 6
obj = MyClass ()
# obj.c


# (. 6 ) StopIteration iterator no more value
= iter (the Range (3))
for i in IT:
    Print (i)
#res = the Next (IT)

# (7) AssertionError assertion (assert) failed
'' '
# guess 3 is greater than 1 a guess? If 3 is greater than 1
# If you guess wrong,Direct Throws
# generally used in the test program
'''
#assert 3<1

"""
if 3<1:
   print("成立")

"""

Two . Exception handling basic grammar

# Format: try:     code1     code2     ... the except:     code1     code2 the possible abnormal code into try this code block them if there is an exceptional error , go directly execpt this block of code









# (1) The basic syntax of exception handling

Example ##. 1:
the try:
    LST = [. 1, 2,. 3,. 4]
    Print (LST [9999]) because there is a list of all # 9999, the program contains errors all
the except:
    Print ( "This program has an error")
    # Pass

# exception process (2) a branch condition execpt +  exception error category specific to this exception error occurs , take the branch # Example 2: the try:     # the following (1) (2) (3) one to one, to a otherwise remove a comment corresponding to the comment will go to the desired program number     # (. 1)     # LST = [1,2,3,45,6]     # Print (LST [10])     # (2)     # = {DIC 'a':. 1}       # Print (DIC [ 'B'])     # (. 3)     Print (HH) the except IndexError:     # (. 1)     Print ( "come here described is the index index reported error bounds . ") the except KeyError:     # (2)     Print (" come here, indicating that the report is a dictionary of key error ") occurs except:
 







    



    










    # (3)
    # conditions are not met, a branch to go except
    print ( "Program error")

# (3) with iterators error bounds by exception class , the receiver generator function returns the return value ## Example 3: DEF mygen ():     the yield. 1     the yield 2     return. 3 # example metaplasia generator generating function generator generating object referred Genl = mygen () the try:     RES = Next (Genl)     RES = Next (Genl)     RES = Next (Genl) the yield # only twice, third time to call all error     Print (RES) # aS in time for a name, give StopIteration class [target] from the name of the except StopIteration aS E:     '' '     when we print the object, triggering __str_ _ magic method     in which StopIteration this class, automatically return the return value of the received abnormal     triggering method __str__ print target, and thus the return value print     '' '     Print (E)




















Three . Active thrown  The raise
BaseExcepton exception is the parent of all classes (base class, the superclass) (alias subclasses:  derived class derived class ) Exception is the parent of all the normal error handling class raise + ( Exception class or objects exception handling ) # format : the try:     the raise the except:     Pass 

  





# Return True .Exception is BaseException subclass
RES = issubclass (Exception, BaseException)
Print (RES)
basic format # (1) raise the syntax
# complete written
try:
    # must be embedded in the code inside try
    The raise BaseException
the except:
    print ( "this program throws an exception")

# shorthand writing
'' '
the try:
    the raise
the except:
    print ( "program throws an exception")

' ''
# (2) custom exception class
# return_errorinfo must rely on the exception get the form to trigger the current line number or file name
DEF return_errorinfo (the n-):
    Import SYS
    f = sys.exc_info () [2] .tb_frame.f_back
    IF the n-== 1:
        return str (f.f_lineno) # returns the current row number
    elif n-== 2:
        return f.f_code.co_filename # Returns the file name

def get_info (n):
    the try:
        The raise BaseException
    the except:
        return return_errorinfo (the n-)

# If you want a custom exception class must inherit all exceptions parent BaseException
class MyException (BaseException):
    DEF __init __ (Self, err_num, ERR_MSG, err_line, err_filename):
        # Print error number
        self.err_num = err_num
        # print an error message
        self.err_msg = ERR_MSG
        # printing error line number
        self.err_line = err_line
        # print error files
        self.err_filename = err_filename

human_sex = "neutral"

the try:
    IF human_sex == "in sex ":
        The raise MyException (1001," human not neutral ", the get_info (. 1), the get_info (2))
the except MyException AS E:
    # printing error number
    print (e.err_num)
    # Print error messages
    Print (e.err_msg)
    # line number printing error
    Print (e.err_line)
    # print the error file
    print (e.err_filename)

 

Add something :

try ... finally .... use the try:     Print (name) # whether or not an error , will be executed finally inside a block of code finally:     Pass if there are some statements, calculated in the case of sending error still want to call or deal with some logic so using the finally # Example: # the try: # Print (name) # # the finally: # Print (123) # Print (456) the try block of code if there are errors, content is not executed else code if no error, then execute the else block content try execpt ... else ... else can not be used in conjunction with separate out and try to use. try ... can be fitted together using the finally .... try ... else ... execpt use try :     #Print (name)     Print (123) the except:     Pass the else:     Print (789) 
































 

Guess you like

Origin www.cnblogs.com/hszstudypy/p/10964102.html